Javascript Class.prototype.method与this.prototype.method
我一直看到Class.prototype.method的示例,但从来没有看到过this.prototype.method的实例。例如:Javascript Class.prototype.method与this.prototype.method,javascript,prototype,Javascript,Prototype,我一直看到Class.prototype.method的示例,但从来没有看到过this.prototype.method的实例。例如: function Class() { this.prototype.method = function() { alert("is this allowed?"); }; } vs 这个原型存在吗 它与Class.prototype相同吗 继承权呢 this.prototype将引用该类对象的实例。因为范围太广,它不会给你带来太
function Class() {
this.prototype.method = function() {
alert("is this allowed?");
};
}
vs
this.prototype将引用该类对象的实例。因为范围太广,它不会给你带来太多好处
prototype正在向类添加功能,而不是向其实例添加功能
类
是一个函数<代码>此是一个对象。函数具有原型
属性;对象不会。在对象上定义了一个\uuuu proto\uuu
属性,但该接口已被弃用。你可以这样做
function Class () {
var prototype = Object.getPrototypeOf(this);
prototype.method = function () {};
}
在构造函数内部,但这并不是一个很好的实践-每次实例化类
,都会在原型上不必要地浪费重写方法
的周期,在代码更复杂的情况下,也可能会浪费内存
简言之,这样做没有好处,也可能有严重的坏处
这个.constructor.prototype应该
this.constructor===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"
并且在使用每个附加实例重新创建方法时,破坏了使用原型的一些好处:
var method = a.method;
console.log(a.method === method); // true
var b = new Class();
console.log(a.method === method); // false
在什么情况下,
this.prototype
将存在?@Pilot当this
是函数的instanceof
或构造函数显式定义this.protoytpe=代码>。否则它将不存在,因为prototype
s是constructor
s的属性,而不是实例的属性。如果开始修改实例上的共享成员,这会有点混乱。您可以通过这个.constructor访问原型。很多情况下都是原型,但你为什么要这么做?也许这个答案可以解释一下原型。
var method = a.method;
console.log(a.method === method); // true
var b = new Class();
console.log(a.method === method); // false