javascript - Arrays and Objects In Prototypes - Not Treated as References -
i have prototype object in javascript, when initialise new instance of prototype , update properties in prototype, updates elements. understand arrays , objects passed reference , wondering of solution around this?
let test = function () {} test.prototype = { array: [], add: function (value) { this.array.push(value) } } let test1 = new test(); let test2 = new test(); test1.add(1); test1.add(2); // prints [1, 2] console.log(test2.array);
one solution be:
class test { constructor() { this.array = [] } add(value) { this.array.push(value) } } let test1 = new test(); let test2 = new test(); test1.add(1); test1.add(2); // prints [] console.log(test2.array);
but not looking es6 approach, more "native" javascript.
thanks help!
that's thing: are treated references.
when this:
test.prototype = { array: [], // <- creates new array , it's being used in instances add: function (value) { this.array.push(value) } }
what want getting different array instances different class instances. in case, this.array = []
in 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); // => []
Comments
Post a Comment