JavaScript字段继承奇怪的行为

时间:2010-08-16 17:30:33

标签: javascript oop

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?

1 个答案:

答案 0 :(得分:2)

这是因为a对象在B的所有实例之间共享(因为B原型是A的实例)。

解决方法是在Test方法中将新对象指定为自己的属性阴影原型链上可用的阴影,例如:

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