我在 Javascript 中有一个原型(prototype)对象,当我初始化原型(prototype)的新实例并更新原型(prototype)中的属性时,它会更新所有元素。我知道数组和对象是通过引用传递的,想知道可以解决这个问题的解决方案吗?
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);
一个解决方案是:
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);
// => []
关于javascript - 原型(prototype)中的数组和对象 - 不被视为引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40485121/