2个不同的实例保持相同的值

当我实例化一个类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); 

有没有人有任何想法,为什么? 谢谢。

原型上的“hello”属性的值是对对象的引用。 每个构造的实例将有权访问该引用,但只涉及一个对象。 因此,通过一个实例对该对象所做的更改将从所有其他实例中可见。

你可以通过添加来看到这个

 console.log(testA.hello === testB.hello); // will log "true" 

如果你想让每个实例拥有它自己的“hello”对象,你必须在构造函数中分配属性。

 var Test = function() { this.hello = { hum: null, ya: null }; };