为什么jQuery在其构造函数实现中执行此操作?

如果我们在http://code.jquery.com/jquery-latest.js上查看最新的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将函数传递给空对象{} ,函数通过this.blah在其上设置东西。

另外从我的理解中, new.apply / .apply等不同,因为返回对象也将原型设置为函数的原型。 所以返回值应该有一个与jQuery.prototype.init.prototype (或jQuery.fn.init.prototype )相同的原型。 但是从我看到它的原型被设置为jQuery.prototype因此所有可用于该集合的命令。

为什么是这样? 我的理解中缺少什么?

如果你仔细看看jQuery的代码 ,你会注意到这一行:

 // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 

这是为了可读性/结构目的,因此构造函数可以有自己的方法。

这里没有真正的“神奇”,只是标准的JavaScript,尽管可能是一种稍微不那么常用的方式。 它在jQuery的情况下非常有用,因为库非常冗长,这为它增加了良好的结构/可读性。

在该源文件中,搜索字符串“将init函数赋予jQuery原型以供以后实例化”:-)

代码将jQuery.fn.initprototype引用设置为jQuery.prototype (我认为这与jQuery.fn相同)。