开发者

JavaScript field Inheritance weird behaviour

function A(){
    this.a = {};
    this.b = 0;
    this.Test = function(value){
        this.a.x = value;
        this.b = value;
    };
}

function B(){}
B.prototype = new A;
开发者_StackOverflow中文版

    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

Why are instances share field a?


This happens because the a object is shared across all instances of B (since the B prototype's is an instance of A).

A workaround would be to assign a new object in your Test method as an own property that shadows the one available on the prototype chain, for example:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜