Turning JSON strings into objects with methods

前端 未结 8 432
抹茶落季
抹茶落季 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.

    0 讨论(0)
  • 2020-12-08 15:31

    JavaScript is prototype based programming language which is classless language where object orientation achieved by process of cloning existing objects that serve as prototypes.

    Serializing JSON would be considering any methods, for instance if you have an object

    var x = {
        a: 4
        getText: function() {
           return x.a;
        }
    };
    

    You will get just { a:4 } where getText method is skipped by the serializer.

    I ran into this same trouble a year back and I had to maintain a separate helper class for each of my domain object and used $.extend() it to my deserialized object when need, just more like having methods to a base class for the domain objects.

    0 讨论(0)
提交回复
热议问题