javascript - Reconstructing JS objects from JSON -


the data of view models is, else's, serialised json across wire.

it understood json.stringify(object) serialises members have non-null value not function. thus, json.parse(json.stringify(someobject)) remove methods object.

my current implementation has each graph node implemented typescript class serialise , deserialise methods. jquery.ajax calls web api , implicitly parses resultant json dag of object definitions, each of has type property indicating type of class prior serialisation. have map of constructors indexed name , appropriate constructor retrieved , data passed constructor parameter.

depending on type there may children; if things proceed recursively down graph.

i have been wondering whether, rather copy property values, couldn't assign appropriate prototype. bring mountain mahomed, might say. eliminate quite bit of clutter in codebase.

as write occurs me use $.extend, i'm progressively weeding jquery out of codebase retrograde step.

  • is there known peril in proposition of diddling prototype?
  • does have better idea? other $.extend, mean. typescripty, preference.

it has been observed in comments assigning prototype means constructor never called. irrelevant. object state set up, required make methods available.

i built object methods content serialized , reconstructed.

i added argument take json object , assign itself.

example using plain object:

function myobject() {    this.valuea = 1;    this.valueb = 2;    this.valuec = 3;      this.add = function() {      return this.valuea + this.valueb + this.valuec;    };  }    var o = new myobject();  console.log(o.add());  console.log(json.stringify(o));

if serialized get:

{"valuea":1,"valueb":2,"valuec":3} 

now, reconstruct can add object.assign() object taking argument , merge self:

function myobject(json) {   this.valuea = 0;   this.valueb = 0;   this.valuec = 0;    this.add = function() {     return this.value1 + this.value2 + this.value3;   };    object.assign(this, json); // merge argument } 

if pass parsed json object argument merge object recreating had:

var json = json.parse('{"valuea":1,"valueb":2,"valuec":3}')    function myobject(json) {    this.valuea = 0;    this.valueb = 0;    this.valuec = 0;      this.add = function() {      return this.valuea + this.valueb + this.valuec;    };      object.assign(this, json); // merge argument  }    var o = new myobject(json);  // reconstruct using original data  console.log(o.add());

if have children via array repeat process recursively down chain.

(a bonus can pass options way).


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -