当我实例化一个类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 };
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句