Javascript 在jQuery源代码中,prototype是什么意思?
例如,从jQuery 1.2.6复制:Javascript 在jQuery源代码中,prototype是什么意思?,javascript,jquery,Javascript,Jquery,例如,从jQuery 1.2.6复制: jQuery.fn = jQuery.prototype = { init: function( selector, context ) { // Make sure that a selection was provided selector = selector || document; .......... }, }; 我在这里读过一些帖子,比如,我知道可以在子类中使用原型来扩展一些方
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
..........
},
};
我在这里读过一些帖子,比如,我知道可以在子类中使用原型来扩展一些方法
但我无法理解上述jQuery代码片段中的用法
是否有描述原型的规范性文件
谢谢。所有对象都有
原型属性。它只是一个对象,其他对象可以从中继承属性。您发布的代码片段只是将一个具有某些属性的对象(例如init
)分配给jQuery
的prototype
,并将别名jQuery.prototype
分配给jQuery.fn
,因为fn
的输入更短更快。如果您暂时忘记了jQuery,请考虑这个简单的例子:
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
alert(this.name + " says hello");
};
var james = new Person("James");
james.sayHello(); // Alerts "James says hello"
在本例中,Person
是一个构造函数。可以通过使用new
操作符调用它来实例化它。在构造函数中,this
关键字引用实例,因此每个实例都有自己的name
属性
Person
的prototype
在所有实例之间共享。因此,Person
的所有实例都有一个从Person.prototype
继承的sayHello
方法。通过将sayHello
方法定义为Person.prototype
的属性,我们节省了内存。我们可以很容易地为Person
的每个实例提供其自己的方法副本(通过将其分配给构造函数中的this.sayHello
),但效率不高
在jQuery中,当调用$
方法时,实际上是在创建jQuery.prototype.init
(请记住jQuery.fn==jQuery.prototype
):
如果您查看jQuery.fn.init
:
jQuery.fn.init.prototype = jQuery.fn;
实际上,您正在创建一个jQuery
实例,它可以访问jQuery.prototype
上声明的所有方法。如前所述,这比在jQuery
的每个实例上声明这些方法要高效得多。请查看标记信息引用。我特别建议您使用雄辩的JavaScript和ECMAScript语言规范。jQuery.fn只是一个名称吗?它与所谓的名称空间有关系吗?fn
是jQuery
对象的属性(就像prototype
只是jQuery
对象的属性一样)。fn
属性和prototype
属性的值都是对单个对象的引用。谢谢!什么是jQuery.fn.init.prototype=jQuery.fn;对于?@liamxu-不客气:)该行导致jQuery.fn.init
继承所有声明为jQuery.fn
属性的方法。因此,当您获得jQuery.fn.init
(这是您通过调用jQuery
获得的)的实例时,它可以访问您所期望的所有常用jQuery方法。这有意义吗?jQuery.fn.init
是一个类(就JavaScript中的“类”而言)。当您使用new
操作符调用它时,它会创建一个jQuery.fn.init
的新实例。这相当令人困惑,因为jQuery.fn.init.prototype
是jQuery.fn
,所以有一个无限循环引用。
jQuery.fn.init.prototype = jQuery.fn;