lia*_* xu 32 javascript jquery
作为一个例子,从jQuery 1.2.6复制:
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
..........
},
};
Run Code Online (Sandbox Code Playgroud)
我在这里读过一些像JavaScript这样的帖子:.extend和.prototype用于什么?并且知道可以在子类中使用原型来扩展一些方法.
但我无法理解jQuery上面片段中的用法.
是否有描述原型的规范文件?
谢谢.
Jam*_*ice 57
所有对象都有prototype属性.它只是一个对象,其他对象可以从该对象继承属性.你已经张贴只需将片段分配一些性质(如一个对象init)到prototype的jQuery,和别名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"
Run Code Online (Sandbox Code Playgroud)
在这个例子中,Person是一个构造函数.它可以通过运算符调用它来实例化new.在构造函数中,this关键字引用实例,因此每个实例都有自己的name属性.
所述prototype的Person是所有实例之间共享.所以,所有的情况下Person有sayHello自己的方法继承从Person.prototype.通过将sayHello方法定义为Person.prototype我们保存内存的属性.我们可以轻松地给出Person它自己的方法副本的每个实例(通过将它分配给this.sayHello构造函数内部),但这不是那么有效.
在jQuery中,当你调用$方法时,你真的在创建一个jQuery.prototype.init(记住jQuery.fn === jQuery.prototype)的实例:
return new jQuery.fn.init(selector, context, rootjQuery);
Run Code Online (Sandbox Code Playgroud)
如果你看看jQuery.fn.init:
jQuery.fn.init.prototype = jQuery.fn;
Run Code Online (Sandbox Code Playgroud)
实际上,您创建的实例jQuery可以访问所有声明的方法jQuery.prototype.如前所述,这比在每个实例上声明这些方法更有效jQuery.
| 归档时间: |
|
| 查看次数: |
33314 次 |
| 最近记录: |