jquery - 为什么 jQuery 对插件使用原型(prototype)属性?

标签 jquery

将插件分配给 jQuery 原型(prototype)属性。当 jQuery 不使用“new”时,这样做有什么意义呢? jQuery 的实例只有一个,不是吗?那么插件不能直接分配给单例 jQuery 对象吗?

最佳答案

插件方法必须自动添加到创建的每个新 jQuery 对象中。

jQuery.fnjQuery.prototype 相同,因此将插件方法分配给 jQuery.fn 会将其添加到 jQuery 原型(prototype)所以每当创建一个新的 jQuery 对象时,该方法将自动可用。从技术上讲,它是一个 jQuery.fn.init 对象,但想法是相同的。

使用如下字符串调用 jQuery:

$(".foo")

创建一个新的 jQuery.fn.init 对象,该对象从 jQuery.fn(定义插件方法的地方)获取其原型(prototype)。

下面是显示创建新对象的相关 jQuery 代码:

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context, rootjQuery );
},


// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

关于jquery - 为什么 jQuery 对插件使用原型(prototype)属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12548952/

相关文章:

javascript - 基于多个类之一的 switch case 语句

javascript - jQuery,使用for循环来操作元素? (添加/删除类(class)等)

javascript - 如果找不到记录,jQuery 隐藏记录标题

jquery - setTimeout() 函数在 jQueryeach() 函数内部不起作用

javascript - 将复选框标记复制到另一个表单

javascript - 奥里莉亚 | json解析无法捕获的异常?

jquery - 使用 jQuery 删除选定的项目

jquery - Express bodyParser 无法解析来自 Internet Explorer 的数据

javascript - 如何强制 knockout 从其绑定(bind)更新模型?

jquery - 在 :fixed tablets only 位置发出