[英]how to override property with prototype
How to override a property with prototype in Javascript?如何在Javascript中使用原型覆盖属性?
function Test(){
this.prop = false;
}
Test.prototype.prop = true;
var T = new Test();
console.log(T.prop);
this returns false
but should return true
??这返回
false
但应该返回true
??
If you need to change the value of the t property access the property directly from an instance of the object or specify it in the constructor.如果您需要更改 t 属性的值,请直接从对象的实例访问该属性或在构造函数中指定它。
Direct Access直接访问
var T = new Test();
t.prop = false;
console.log(T.prop);
Constructor构造函数
function Test(prop){
this.prop = prop;
}
var T = new Test(false);
The constructor is executed after the prototype copy.构造函数在原型复制之后执行。 You can't override a property setted by a constructor by using the prototype.
您不能使用原型覆盖由构造函数设置的属性。
But if you really want to do this, you can do this :但如果你真的想这样做,你可以这样做:
function Test(){
if (this.prop === undefined) {
this.prop = false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.