Javascript 为什么jQuery在其构造函数实现中会这样做?
如果查看最新的jQuery源代码,我们会看到以下内容:Javascript 为什么jQuery在其构造函数实现中会这样做?,javascript,jquery,Javascript,Jquery,如果查看最新的jQuery源代码,我们会看到以下内容: var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context ); } 我对Javascript中新关键字的理解基本上是Javascript将空对象{}传递给函数,函数
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
}
我对Javascript中新关键字的理解基本上是Javascript将空对象{}
传递给函数,函数通过this.blah
在其上设置内容
根据我的理解,新的
与不同。调用
/。应用
等。。因为返回对象也将原型设置为函数的原型。因此,返回值应该有一个与jQuery.prototype.init.prototype
(或jQuery.fn.init.prototype
)相同的原型。然而,从我看到它的prototype被设置为jQuery.prototype
,因此所有可用的命令都可以在这个集合上工作
为什么会这样?在我的理解中,我遗漏了什么?在该源文件中,搜索字符串“为init函数提供jQuery原型以供以后实例化”:-) 代码将
jQuery.fn.init
的prototype
引用设置为jQuery.prototype
(我认为这与jQuery.fn
相同)。如果深入研究,您会注意到这一行:
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
这是为了可读性/结构目的,因此构造函数可以有自己的方法
这里没有真正的“魔力”,只有标准的JavaScript,尽管可能是以一种稍微不常用的方式。它在jQuery中很有用,因为库相当长,这为它增加了良好的结构/可读性