3
我的最終任務是完全恢復對象使用JSON以前保存。目前JSON只允許恢復數據,但不允許行爲。 possilbe的解決方案是創建一個新的對象(讓我們稱之爲obj)並將數據從JSON-recovered-object複製到obj。但它對我來說並不好看。我問的是,有沒有辦法在JavaScript中動態更改對象原型?動態變化的原型JavaScript對象
這就是我(用自制的複製方法)目前解決問題:
function Obj() {
this.D = "D";
this.E = "E";
this.F = "F";
this.toString = function() {
return this.D + " * " + this.E + " * " + this.F;
};
this.copy = function (anotherObj) {
for (var property in anotherObj) {
if (isDef(anotherObj[property]) && isDef(this[property])) {
this[property] = anotherObj[property];
}
}
}
}
;
$(document).ready(function() {
var str = $.toJSON(new Obj());
$("#result").append("<p>JSON: " + str + "</p>");
var obj = new Obj();
obj.copy($.parseJSON(str));
$("#result").append("<p>Recovered obj: " + obj.toString() + "</p>");
});
function isDef(variable)
{
return typeof variable !== undefined;
}
感謝。這正是我所期待的。很遺憾它沒有,如果有對象下地幹活:http://jsfiddle.net/mr_goodcat/KfQrc/2/ – 2012-03-06 08:13:27
更新:看來「深拷貝」應該是一個解決方案,但我不能使它工作在行爲的一部分(數據恢復): http://jsfiddle.net/mr_goodcat/KfQrc/3/ – 2012-03-06 08:36:17
呀,我不能得到那個工作,無論是。複製嵌套的原型目前非常棘手,超出了我的想象。 – GregL 2012-03-06 09:04:50