I have a prototype object in Javascript, when I initialise a new instance of the prototype and update properties in the prototype, it updates for all elements. I understand that
That's the thing: they are treated as references.
When you do this:
Test.prototype = {
array: [], // <- This creates a new array and it's being used in all instances
add: function (value) {
this.array.push(value)
}
}
What you want is getting different array instances for different class instances. In that case, simply do this.array = []
in your constructor:
let Test = function () { this.array = []; }
let Test = function () { this.array = []; }
Test.prototype = {
array: [],
add: function (value) {
this.array.push(value)
}
}
let test1 = new Test();
let test2 = new Test();
test1.add(1);
test1.add(2);
console.log(test1.array);
// => [1, 2]
console.log(test2.array);
// => []