我在实例化一个类 2 次时遇到问题。第二个实例只保留第一个实例的参数。
这是一个简单的例子:
var Test = function() {};
Test.prototype = {
bonjour: null,
hello: {
hum: null,
ya: null,
},
};
var testA = new Test();
testA.bonjour = 'Aaa';
testA.hello.hum = 'Bbb';
// return "Aaa"
console.log(testA.bonjour);
// return "{ hum: 'Bbb', ya: null }"
console.log(testA.hello);
console.log('');
var testB = new Test();
// return "null" -> ok
console.log(testB.bonjour);
// return "{ hum: 'Bbb', ya: null }" -> wtf ?!
console.log(testB.hello);
有人知道为什么吗? 谢谢。
最佳答案
原型(prototype)上“hello”属性的值是对对象的引用。每个构造的实例都可以访问该引用,但只涉及一个对象。因此,通过一个实例对该对象所做的更改将对所有其他实例可见。
你可以通过添加看到这个
console.log(testA.hello === testB.hello); // will log "true"
如果您希望每个实例都有自己的“hello”对象,则必须在构造函数中分配该属性。
var Test = function() {
this.hello = { hum: null, ya: null };
};
关于javascript - 2个不同的实例保持相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28033101/