function A(){
this.a = {};
this.b = 0;
this.Test = function(value){
this.a.x = value;
this.b = value;
};
}
function B(){}
B.prototype = new A;
var b1= (new B());
b1.Test(1);
var b2= (new B());
b2.Test(2);
log(b1.b == 1); //true
log(b2.b == 2); //true
log(b1.a.x == 1);//false x == 2
log(b2.a.x == 2);//true
为什么实例共享字段a?
最佳答案
发生这种情况是因为 a
对象在 B
的所有实例之间共享(因为 B
原型(prototype)是 A 的实例
)。
解决方法是在您的 Test
方法中分配一个新对象作为自己的属性,隐藏原型(prototype)链上可用的对象,例如:
function A(){
this.a = {};
this.b = 0;
this.Test = function(value){
this.a = {x: value}; // shadow the object on the prototype chain
this.b = value;
};
}
function B(){}
B.prototype = new A;
var b1= new B();
b1.Test(1);
var b2= new B();
b2.Test(2);
console.log(b1.b == 1); //true
console.log(b2.b == 2); //true
console.log(b1.a.x == 1);//true
console.log(b2.a.x == 2);//true
关于JavaScript 字段继承奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3495648/