【问题标题】:Why jQuery do this: jQuery.fn.init.prototype = jQuery.fn?为什么 jQuery 这样做:jQuery.fn.init.prototype = jQuery.fn?
【发布时间】:2010-12-17 19:48:36
【问题描述】:

小问题是为什么 jQuery 这样做

jQuery.fn = jQuery.prototype = {
init: function() {...},
    f1: function() {...},
    ...
};
jQuery.fn.init.prototype = jQuery.fn;

为什么不简单地将f1() 等添加到init.prototype 中呢?仅仅是审美还是有一些深刻的想法?

【问题讨论】:

  • 我不确定您将 f1() 添加到 init.prototype 中是什么意思?它不是在“添加”任何东西,而是在分配原型。
  • 当然。我的意思是“分配”当然。对不起我的英语不好。问题是为什么不简单地将所有函数分配给 init.prototype?为什么他们分配给 jQuery.prototype 而不是 jQuery.prototype 分配给 jQuery.prototype.init.prototype
  • jQuery的设计模式相关问题:stackoverflow.com/q/12143590/1048572

标签: javascript jquery


【解决方案1】:

函数jQuery.fn.init 是在您调用jQuery(".some-selector")$(".some-selector") 时执行的函数。您可以在来自jquery.js 的这个 sn-p 中看到这一点:

jQuery = window.jQuery = window.$ = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
}

所以,事实上,你提到的那一行对于 jQuery 如何允许向 jQuery 对象添加功能至关重要,无论是在 jQuery 本身内部还是从插件中。这是一行:

jQuery.fn.init.prototype = jQuery.fn;

通过将jQuery.fn 指定为该函数的原型(并且因为第一个sn-p 使用'new' 将jQuery.fn.init 视为构造函数),这意味着通过jQuery.fn.whatever 添加的功能立即可用在所有 jQuery 调用返回的对象上。

例如,可以像这样创建和使用一个简单的 jQuery 插件:

jQuery.fn.foo = function () { alert("foo!"); };
jQuery(".some-selector").foo();

当您在第一行声明“jQuery.fn.foo”时,您实际上是在将该函数添加到使用 jQuery 函数创建的所有 jQuery 对象的原型中,就像第二行中的那样。这允许您对 jQuery 函数的结果简单地调用 'foo()' 并调用您的插件函数。

简而言之,如果 jQuery 中不存在这一行,那么如果实现细节发生变化,那么编写 jQuery 插件会更加冗长,并且将来会受到破坏。

【讨论】:

  • 这是我这么长时间以来读过的最有启发性的评论。谢谢。
  • 很抱歉在 answer/cmets 中注入了一个问题,但我们是说以这种方式向 jQuery 添加一个函数会使页面上的每个元素都可以使用该函数吗?它是否使该功能可用于元素以外的事物,例如其他 jQuery 对象等?而且,“jQuery = window.jQuery = window.$ = function(...”仅仅是一种表明这三个是等效语法的方式吗?或者这实际上是你会做的事情吗?
【解决方案2】:

jQuery.fn 只是 jQuery.prototype 的别名。我想它是出于美观和减少打字的原因而定义的。

所以

jQuery.fn.init.prototype = jQuery.fn;

其实是

jQuery.prototype.init.prototype = jQuery.prototype;

为什么需要这样做,这个forum post很有帮助:

它赋予 init() 函数相同的功能 原型作为 jQuery 对象。所以 当您将 init() 作为构造函数调用时 在“返回新的 jQuery.fn.init( 选择器,上下文 );" 语句,它 将该原型用于它的对象 结构体。这让 init() 替换 jQuery 构造函数 自己。

您实现的是从 jQuery.fn.init 构造函数返回的对象可以访问 jQuery 方法。

【讨论】:

  • 是的。我知道.fn.prototype 的快捷方式。但是为什么他们扩展了 jQuery.prototype 并且这样做了jQuery.fn.init.prototype = jQuery.fn?为什么不直接扩展jQuery.fn.init.prototype
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多