你可以寫一個深克隆方法,你的對象的每個屬性的每個值拷貝到一個新的。
注我延長Object.prototype中,以避免類型檢查和純樸的緣故,這可以改變,如果你覺得如意它
Object.defineProperty(Object.prototype, "clone", {
enumerable : false,
value: function(deep) {
deep |= 0;
var type = typeof this;
if (type !== "object") {
return this.valueOf();
}
var clone = {};
if (0 === deep) {
for (var prop in this) {
clone[prop] = this[prop];
}
} else {
for (var prop in this) {
if (typeof this[prop] !== "undefined" && this[prop] !== null)
clone[prop] = (typeof this[prop] !== "object" ? this[prop] : this[prop].clone(deep - 1));
else
clone[prop] = "";
}
}
return clone;
}
});
Object.defineProperty(Array.prototype, "clone", {
enumerable : false,
value:function(deep) {
deep |= 0;
var clone = [];
if (0 === deep)
clone = this.concat();
else
this.forEach(function(e) {
if (typeof e !== "undefined" && e !== null)
clone.push((typeof e !== "object" ? e : e.clone(deep - 1)));
else
clone.push("");
});
return clone;
}
});
示例輸出和Demo
var first = {
var1:0,
var2:0
var3:0
};
var second = first.clone(Infinity);
first.var1++;
console.log (first.var1,second.var1,second); //1 , 0
要將此應用於您的代碼,您只需克隆對象app.Defaults = app.Variables.clone()
第一個參數是深度級別。如果省略,則只克隆第一級,在這種情況下就足夠了。
您應該執行[深克隆] [1] [1]:http://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript –
相關:http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-an-object,http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a -javascript對象。 –
看到這個線程http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Belyash