为什么jQuery要返回jQuery.fn.init对象

2025-05-10 00:26:04
推荐回答(1个)
回答1:

下面这两段是jQuery里面,你想了解的最核心部分
1
2
3
4
5
6
7
8
9
10
11
12
jQuery = window.jQuery = window.$ = function (x, y)
{
return new jQuery.fn.init(x, y);
};
jQuery.fn = jQuery.prototype =
{
init: function()
{
// some logic for object initialization
return this;
}
};
从这段代码我们可以看出:
jQuery()实际上就是jQuery.fn.init()
jQuery.fn和jQuery.prototype一样,实际上就是一个jQuery对象的一个原型的定义
这两段代码的作用实际上就是要让用户使用jQuery()或者$.jQuery()的时候,就完成对jQuery对象的初始化,不需要在动态的去调用init方法