如何在Javascript中使用原型覆盖属性?
function Test(){
this.prop = false;
}
Test.prototype.prop = true;
var T = new Test();
console.log(T.prop);
这会返回false
,但应该返回true
??
答案 0 :(得分:0)
如果需要更改t属性的值,则直接从对象的实例访问该属性,或在构造函数中指定它。
直接访问
var T = new Test();
t.prop = false;
console.log(T.prop);
构造强>
function Test(prop){
this.prop = prop;
}
var T = new Test(false);
答案 1 :(得分:0)
构造函数在原型副本之后执行。您不能使用原型覆盖构造函数设置的属性。
但如果你真的想这样做,你可以这样做:
function Test(){
if (this.prop === undefined) {
this.prop = false;
}
}