如果我们查看最新的 jQuery 源代码http://code.jquery.com/jquery-latest.js 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关键字的理解本质上是JavaScript向函数传递一个空对象{}
该函数通过以下方式在其上设置内容this.blah
.
也以我的理解new
不同于.call
/.apply
等等......因为返回对象也将原型设置为函数的原型。所以返回值应该有一个与以下相同的原型jQuery.prototype.init.prototype
(or jQuery.fn.init.prototype
)。然而,据我所知,它的原型被设置为jQuery.prototype
因此,所有命令都可在该集合上工作。
为什么是这样?我的理解中缺少什么?
如果你深入研究jQuery 的代码 http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js,你会注意到这一行:
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
这是出于可读性/结构目的,因此构造函数可以有自己的方法。
这里并没有真正的“魔法”,只是标准的 JavaScript,尽管可能是以一种不太常用的方式。它在 jQuery 的情况下很有用,因为该库相当长,这为其增加了良好的结构/可读性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)