为什么jQuery在其构造函数实现中这样做?

5
如果我们查看最新的jQuery源代码,可以在http://code.jquery.com/jquery-latest.js中找到以下内容:
var jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
}

我的理解是,在JavaScript中,new关键字会传递一个空对象{}给函数,并通过this.blah在这个对象上设置一些东西。此外,我认为new.call/.apply等不同之处在于返回的对象也具有与函数相同的原型。因此,返回值应该具有与jQuery.prototype.init.prototype(或jQuery.fn.init.prototype)相同的原型。但是,从我所看到的,它的原型设置为jQuery.prototype,因此所有可用于操作集合的命令都可以使用。
为什么会这样呢?我的理解是否有误?
2个回答

1
如果你深入了解jQuery的代码,你会注意到这一行:
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

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

这里没有真正的“魔法”,只是标准的JavaScript,尽管可能使用得不太常见。在jQuery的情况下很有用,因为该库非常庞大,这样做可以增加良好的结构性和可读性。


0
在该源文件中,搜索字符串“将jQuery原型传递给init函数以供稍后实例化” :-)
该代码将jQuery.fn.initprototype引用设置为jQuery.prototype(我认为与jQuery.fn相同)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接