我是 reading this article about how jQuery works ,那篇文章将 jquery 结构缩小为符号代码:
/*1*/ var jQuery = (function ()
/*2*/ {
/*3*/
/*4*/
/*5*/ var jQuery = function (selector, context)
/*6*/ {
/*7*/
/*8*/
/*9*/ return new jQuery.fn.init(selector, context, rootjQuery);
/*10*/ },
/*11*/ rootjQuery;
/*12*/
/*13*/
/*14*/ jQuery.fn = jQuery.prototype = {
/*15*/ constructor: jQuery,
/*16*/ init: function (selector, context, rootjQuery)
/*17*/ {
/*18*/
/*19*/ if (!selector)
/*20*/ {
/*21*/ return this;
/*22*/ }
/*23*/ },
/*24*/ //I screwed with the core!
/*25*/
/*26*/ yo: function ()
/*27*/ {
/*28*/ alert("yo")
/*29*/ },
/*30*/ };
/*31*/
/*32*/ jQuery.fn.init.prototype = jQuery.fn;
/*33*/
/*34*/ // Expose jQuery to the global object
/*35*/ return jQuery;
/*36*/ })();
#32
行是奇迹发生的地方。因此,当我编写 jQuery(..)
时,它实际上运行了 new init()
,它可以访问所有 jQuery.fn
函数。
很清楚(大部分),但我有 2 个问题:
问题 #1 为什么行 #15
(constructor: jQuery,
) 存在?它所做的(恕我直言)就是告诉 prototype
对象它的 ctor 函数
是 jQuery
。 jQuery 如何使用这个事实?
问题 #2 查看 #14
行,显然是在向 jQUery.fn
添加函数( function yo
在我们的示例中 - #26
行)。
但是为什么 jQuery.prototype
(第 14 行中间)也有这些功能(它将它们设置为它的 prototype
... )?就像我们要执行 $.addClass()
一样,无效。
最佳答案
Why does line #15 (
constructor: jQuery,
) exist? all it does (imho) is to tell the prototype object that it's ctor function is jQuery.
是的。人们确实期望找到 new jQuery().constructor == jQuery
。
how does jQuery use that fact ?
例如,pushStack
internal method uses this.constructor()
创建新实例 - 这也允许 inheritance from jQuery .
But why does jQuery.prototype (line #14 middle) also have these [jQuery.fn] functions (it sets them to it's prototype...)?
引用this answer :
One of the reasons behind this is certainly that they want to accomodate people that might modify
jQuery.prototype
instead ofjQuery.fn
.However another valid reason is that they perhaps wanted
somejQueryObj instanceof jQuery
to returns true, while it normally wouldn't.
It's like we're going to do
$.addClass()
which is invalid.
没有,怎么会?您是否混淆了每个(构造函数)函数的标准 .prototype
属性与内部原型(prototype)链?
关于javascript - jQuery 结构 - 澄清?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22248997/