1

I'm not an expert in js. But recently I started writing with prototypes and faced with such issue.

I have class Test and object (attributes) like a property of this class. Then I create instances collection with different attributes. Unfortunately, I get collection with the same attributes, which are the same with last instance attributes. I suppose it's easier to understand when you see the code.

function Test(id) {
   this.init(id);
}

Test.prototype = {
    attributes : {
        id : null,
    },

    init : function (id) {
        this.attributes.id = id;
    }
};

var a = [0, 1, 2, 3, 4];
var b = {};


for(var i in a) {
    b[i] = new Test(a[i]);
}

console.log(b);

this result I have

Could you explain me a cause and how can I avoid this trouble? Thanks a lot

melpomene
  • 84,125
  • 8
  • 85
  • 148
andrew
  • 68
  • 1
  • 8

1 Answers1

2

The prototype is shared between each of the instances of Test. For this reason, once it is set in any of the instances, it is also changed for all other instances.

To avoid this, you can make the id an attribute of the instance itself, not of the prototype:

function Test(id) {
    this.init(id);
}
    
Test.prototype = {
    init : function (id) {
        this.id = id;
    }
};
    
var a = [0, 1, 2, 3, 4];      
    
for(var i in a) {
    console.log(new Test(a[i]));
}
    

By not declaring the id as an attribute of the prototype, it is by default treated as an attribute of the instance.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94