原型中的数组和对象 – 不作为参考处理

我有一个JavaScript的原型对象,当我初始化一个新的原型实例和更新原型的属性,它更新所有元素。 我明白,数组和对象通过引用传递,并想知道一个解决scheme,会让你在这个?

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); 

一个解决scheme是:

 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); 

但我不是在寻找一个ES6的方法,更“本土”的JavaScript。

谢谢您的帮助!

这是事情:他们视为参考。

当你这样做:

 Test.prototype = { array: [], // <- This creates a new array and it's being used in all instances add: function (value) { this.array.push(value) } } 

你想要的是为不同的类实例获取不同的数组实例。 在这种情况下,只需在构造函数中执行this.array = []

 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); // => [] 

在构造函数中初始化可变成员,而不是在原型中。 如果它在原型中,它将在所有实例之间共享:

 let Test = function () { this.array = []; } Test.prototype = { 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); console.log(test2.array); 

在实例上而不是在原型上定义数组:

 function Test() { this.array = []; } Test.prototype.add = function (value) { this.array.push(value) } 

我明白,数组和对象通过引用传递

不,他们不是。 但是它们被对象引用所引用,这是一个完全不同的事情, 1的确是你遇到的问题。

并想知道一个解决scheme,会让你在这附近?

做你在ES6方法中所做的事:把它放在对象本身,而不是原型:

 let Test = function () { this.array = []; }; 

1 (所有这些概念“通过引用传递”和“对象引用”的共同之处在于它们都使用“引用”一词。前者是对variables的引用[而JavaScript没有的概念]在后者中,这是对一个对象的引用。)