005*_*005 22 javascript prototype
我一直看到Class.prototype.method的例子,但从来没有看过this.prototype.method的例子.例如:
function Class() {
this.prototype.method = function() {
alert("is this allowed?");
};
}
Run Code Online (Sandbox Code Playgroud)
VS
function Class() {}
Class.prototype.method = function() {
alert("traditional example");
};
Run Code Online (Sandbox Code Playgroud)
Jon*_*ski 19
this.prototype存在吗?
不,但是,this.constructor.prototype应该.
它与Class(.constructor).prototype相同吗?
它通常具有相同的值(只要this.constructor === Class),但意图不同.
继承怎么样?
每个new Class实例都将继承自Class.prototype.因此,prototype对象适用于定义所有实例都可访问的共享值.然后,构造函数只需设置对每个实例唯一的状态.
但是,尝试混合2并prototype在构造函数中设置属性有一些问题,包括鸡或蛋冲突,因为在创建第一个实例之前该方法不会存在:
function Class() {
this.constructor.prototype.method = function () {};
}
console.log(typeof Class.prototype.method); // "undefined"
var a = new Class();
console.log(typeof Class.prototype.method); // "function"
Run Code Online (Sandbox Code Playgroud)
并且失败了prototype使用每个附加实例重建方法的一些好处:
var method = a.method;
console.log(a.method === method); // true
var b = new Class();
console.log(a.method === method); // false
Run Code Online (Sandbox Code Playgroud)