我在Javascript中有一个原型对象,当我初始化原型的新实例并更新原型中的属性时,它会更新所有元素。我理解数组和对象是通过引用传递的,并且想知道一个可以解决这个问题的解决方案吗?
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。
感谢您的帮助!
答案 0 :(得分:2)
就是这样:他们被视为参考。
执行此操作时:
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);
// => []
答案 1 :(得分:1)
在构造函数中初始化可变成员,而不是在原型中。如果它在原型中,它将在所有实例之间共享:
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);
答案 2 :(得分:1)
在实例上而不是在原型上定义数组:
function Test() {
this.array = [];
}
Test.prototype.add = function (value) {
this.array.push(value)
}
答案 3 :(得分:1)
我理解数组和对象是通过引用传递的
不,他们不是。但它们被对象引用引用,这是一个完全不同的东西, 1 ,确实是你遇到的问题。
并且想知道一个可以解决这个问题的解决方案吗?
完全按照ES6方法做的:把它放在对象本身上,而不是原型上:
let Test = function () {
this.array = [];
};
1 (所有概念“通过引用传递”和“对象引用”的共同之处在于它们都使用“引用”一词。在前者中,它是对变量 [和JavaScript没有的概念]。在后者中,它是对象的引用。)