Turning JSON strings into objects with methods

前端 未结 8 500
抹茶落季
抹茶落季 2020-12-08 14:30

I have an app that allows users to generate objects, and store them (in a MySQL table, as strings) for later use. The object could be :

function Obj() {
             


        
8条回答
  •  星月不相逢
    2020-12-08 15:29

    You can indeed create an empty instance and then merge the instance with the data. I recommend using a library function for ease of use (like jQuery.extend).

    You had some errors though (function ... = function(...), and JSON requires keys to be surrounded by ").

    http://jsfiddle.net/sc8NU/1/

    var data = '{"label": "new object"}';  // JSON
    var inst = new Obj;                    // empty instance
    jQuery.extend(inst, JSON.parse(data)); // merge
    

    Note that merging like this sets properties directly, so if setLabel is doing some checking stuff, this won't be done this way.

提交回复
热议问题