如果我们在 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 中 new 关键字的理解本质上是 JavaScript 向函数传递一个空对象 {}
该函数通过 this.blah
在其上设置内容.
也是我的理解new
不同于 .call
/.apply
等等。因为返回对象也将原型(prototype)设置为函数的原型(prototype)。所以返回值应该有一个与jQuery.prototype.init.prototype
相同的原型(prototype)(或 jQuery.fn.init.prototype
)。但是据我所知,它的原型(prototype)设置为 jQuery.prototype
因此所有可用于集合的命令。
这是为什么?我的理解中缺少什么?
最佳答案
如果你深入研究 jQuery's code ,您会注意到这一行:
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
这是出于可读性/结构的目的,因此构造函数可以有自己的方法。
这里并没有真正的“魔法”,只是标准的 JavaScript,尽管也许是以一种不太常用的方式。它在 jQuery 的情况下很有用,因为库非常冗长,这增加了良好的结构/可读性。
关于javascript - 为什么 jQuery 在其构造函数实现中这样做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2477370/