2012-03-06 50 views
3

我的最終任務是完全恢復對象使用JSON以前保存。目前JSON只允許恢復數據,但不允許行爲。 possilbe的解決方案是創建一個新的對象(讓我們稱之爲obj)並將數據從JSON-recovered-object複製到obj。但它對我來說並不好看。我問的是,有沒有辦法在JavaScript中動態更改對象原型?動態變化的原型JavaScript對象

這就是我(用自制的複製方法)目前解決問題:

(this code on JSFiddle)

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; 
} 

回答

4

有許多流行的JS庫提供更簡單的方法。

例如,如果你使用jQuery,您可以使用jQuery.extend()方法,而不是你的複製功能,像這樣:

var obj = $.extend(new Obj(), $.parseJSON(str)); 

歧路的jsfiddle here

編輯:基於從this question的想法,我是能夠得到恢復的對象都嵌套功能好,看到updated jsFiddle

的核心思想是利用原型代替性能,並確保從JSON(這僅僅是數據)恢復的對象是第一參數$.extend()

function Obj2() { 
    this.A = "A"; 
} 
Obj2.prototype.toString = function() { 
    return this.A; 
}; 

function Obj() { 
    this.A = new Obj2(); 
    this.D = "D"; 
    this.E = "E"; 
    this.F = "F"; 
} 
Obj.prototype.toString = function() { 
    return this.A.toString() + " * " + this.D + " * " + this.E + " * " + this.F; 
}; 

var str = $.toJSON(new Obj()); 
$("#result").append("<p>JSON: " + str + "</p>"); 
var obj = jQuery.extend($.parseJSON(str), new Obj()); 
$("#result").append("<p>Recovered obj: " + obj.toString() + "</p>"); 
+0

感謝。這正是我所期待的。很遺憾它沒有,如果有對象下地幹活:http://jsfiddle.net/mr_goodcat/KfQrc/2/ – 2012-03-06 08:13:27

+0

更新:看來「深拷貝」應該是一個解決方案,但我不能使它工作在行爲的一部分(數據恢復): http://jsfiddle.net/mr_goodcat/KfQrc/3/ – 2012-03-06 08:36:17

+0

呀,我不能得到那個工作,無論是。複製嵌套的原型目前非常棘手,超出了我的想象。 – GregL 2012-03-06 09:04:50