tags:

views:

27

answers:

1
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

Why are instances share field a?

+1  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
CMS
>This happens because the a object is shared across all instances of B.But why it works with b field? Why object is shared but simple types not?
dotneter
@dotneter: `a` is an object, by doing: `this.a.x = value;` you are modifying the inherited object, shared by all instances, by assigning `this.b = value;` you are creating an own property in the current object (`this`), shadowing the inherited one, just like in my example I do `this.a = {x: value};`, a new property is created on the object that `this` points to.
CMS