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

5 javascript 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 );
}
Run Code Online (Sandbox Code Playgroud)

我对Javascript中新关键字的理解本质上是JavaScript将函数传递给一个空对象{},函数通过它设置东西this.blah.

从我的理解也new不同于.call/ .applyetc ..因为返回对象也将原型设置为函数的原型.因此返回值应该具有与jQuery.prototype.init.prototype(或jQuery.fn.init.prototype)相同的原型.然而,从我看到它的原型被设置为jQuery.prototype因此所有可用于该集合的命令.

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

Dan*_*ert 1

如果您深入研究jQuery 的代码,您会注意到这一行:

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
Run Code Online (Sandbox Code Playgroud)

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

这里并没有真正的“魔法”,只是标准的 JavaScript,尽管可能是以一种不太常用的方式。它在 jQuery 的情况下很有用,因为该库相当长,这为其增加了良好的结构/可读性。