【发布时间】: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 function 是jQuery。 jQuery 是如何利用这个事实的?
问题 #2 查看#14 行,它显然是在向jQUery.fn 添加函数(在我们的示例中为函数yo - 行#26)。
但是为什么jQuery.prototype(第14行中间)也有这些功能(它将它们设置为prototype...)?就像我们要执行 $.addClass() 这是无效。
【问题讨论】:
-
@Bergi 您的回答没有回答我的问题 #1。你只是描述事实。而已。关于我的问题 #2,我不明白你的措辞:“对于那些不使用 fn 属性的人” - 你能详细说明一下吗?
-
好的,我来一个更具体的答案
标签: javascript jquery