2014-03-07 40 views
5

reading this article about how jQuery works,这条精缩jQuery的结构为象征代码:#32jQuery结构 - 澄清?

/*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*/ })(); 

行是魔法发生。所以当我写jQuery(..)它实际上运行new init()有权访问所有jQuery.fn函数。

这是很清楚的(大部分),但我有2个问题:

问题#1为什么存在线#15constructor: jQuery,)?它所做的(imho)是告诉prototype对象它的ctor functionjQuery。 jQuery如何使用这个事实?

问题2纵观线#14,这显然(在我们的例子功能yo - 线#26)添加功能jQUery.fn

但是为什么jQuery.prototype(线#14中)具有这些功能(它设置他们是prototype ...)?这就像我们要做$.addClass()这是无效

+0

[差异的价值,原型和属性]可能的重复(http://stackoverflow.com/questions/12143590/difference-of-the-value-prototype-and-property) – Bergi

+0

@Bergi您的答案不回答我的问题#1。你只是描述了这个事实。而已。关于我的问题#2,我不会在那里写下你的措辞:“对于那些不使用fn财产的人” - 你能否详细说明一下? –

+2

好吧,我会带更具体的答案 – Bergi

回答

2

为什么第15行(constructor: jQuery,)存在?它所做的(imho)是告诉原型对象它的ctor函数是jQuery。

是的。人们希望找到new jQuery().constructor == jQuery

jQuery如何使用该事实?

例如,pushStack internal methoduses this.constructor()创建新实例 - 这也让inheritance from jQuery

但为什么jQuery.prototype(第14行中间)也有这些[jQuery.fn]功能(它将它们设置为它的原型...)?

this answer

一个背后的原因肯定是他们要 适应人们可能会改变jQuery.prototype代替 jQuery.fn

然而另一个有效的原因是,他们也许想 somejQueryObj instanceof jQuery到返回true,而它 通常不会。

这就像我们要做的$.addClass()这是无效的。

不,这是怎么回事?您是否将每个(构造函数)函数的标准.prototype属性与内部原型链混淆?

+0

关于你在这里的最后回复 - 我不明白。我的意思是:如果具有所有功能的对象被设置为'jQuery.fn' - 没关系。但他们也将这个对象的所有功能都设置为'jQuery.prototype.' - 为什么? '$(div).addClass()'不应该在'$ .addClass()'上工作 - 我能理解吗? –

+0

为什么你认为'jQuery.prototype.addClass = ...'会使'$ .addClass'工作? – Bergi

+0

我没有看到你的演示负责哪一行:'somejQueryObj instanceof jQuery'。我的意思是 - 'somejQueryObj'就像'$()',它的内部就像'new init()'。那么'jQuery.fn.init.prototype'和'jQuery.prototype'(原型继承)之间的连接在哪里?你能告诉我那条路吗? –