【问题标题】:jQuery structure - clarification?jQuery结构 - 澄清?
【发布时间】:2014-04-10 12:51:33
【问题描述】:

我是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 函数。

很清楚(大部分),但我有两个问题:

问题 #1 为什么行 #15 (constructor: jQuery,) 存在?它所做的一切(恕我直言)就是告诉prototype 对象它是ctor functionjQuery。 jQuery 是如何利用这个事实的?

问题 #2 查看#14 行,它显然是在向jQUery.fn 添加函数(在我们的示例中为函数yo - 行#26)。

但是为什么jQuery.prototype(第14行中间)有这些功能(它将它们设置为prototype...)?就像我们要执行 $.addClass() 这是无效

【问题讨论】:

  • @Bergi 您的回答没有回答我的问题 #1。你只是描述事实。而已。关于我的问题 #2,我不明白你的措辞:“对于那些不使用 fn 属性的人” - 你能详细说明一下吗?
  • 好的,我来一个更具体的答案

标签: javascript jquery


【解决方案1】:

为什么第 15 行 (constructor: jQuery,) 存在?它所做的一切(恕我直言)就是告诉原型对象它的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 返回真,而它 通常不会。

就像我们要执行 $.addClass() 一样,这是无效的。

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

【讨论】:

  • 关于您最后的回复-我不明白。我的意思是:如果将具有所有功能的对象设置为jQuery.fn-很好。但他们还将这个具有所有功能的对象设置为jQuery.prototype. - 为什么? $(div).addClass() 不应该在 $.addClass() 上工作 - 我明白了吗?
  • 为什么你认为jQuery.prototype.addClass = … 会让$.addClass 工作?
  • 我看不到哪一行负责您的演示:somejQueryObj instanceof jQuery。我的意思是 - somejQueryObj 就像 $() 又像 new init() 。那么jQuery.fn.init.prototypejQuery.prototype (原型继承)之间的联系在哪里 - 请告诉我那条路径吗?
  • 连接是jQuery.fn.init.prototype === jQuery.prototype...
  • Bergi - 我在代码中看到的只是jQuery.fn.init.prototype=jQuery.fn。我没有看到x.prototype=y.prototype...再次,请你告诉我那条线在哪里?还是#32和#14的组合?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多