直到今天我才知道這個問題,我想知道繞過它的最好方法是什麼。問題是,當你從相同的構造函數實例化兩個不同的對象時,它們共享相同的原型,這意味着如果一個對象設置了原型,所有其他對象也將被改變。在JS對象的不同實例之間正確隔離數據
例如:
function A(obj) {
}
A.prototype = {
events: {
one: 1
}
};
var b = new A();
console.log(b.events);
var c = new A();
console.log(c.events);
b.events.x = 2;
console.log(b.events);
console.log(c.events); //whoops, c also got b's event x
究竟發生了什麼?解決這個問題的最佳方法是什麼?
這是我想出的,但我想知道是否有更好的方法?
var _ = require('underscore');
function A(obj) {
if (obj == null) {
obj = {};
}
if(obj.events == null){
obj.events = {};
}
this.events = _.extend(obj.events, A.prototype.events);
}
A.prototype = {
events: {
one: 1
}
};
var b = new A({events:{three:3}});
console.log(b.events);
var c = new A({events:{four:4}});
console.log(c.events);
b.events.x = 2;
console.log(b.events);
console.log(c.events); //now it's better...(this is crazy)