How do you serialize javascript objects with methods using JSON?

前端 未结 3 1415
旧巷少年郎
旧巷少年郎 2020-12-21 12:03

I am looking for an enhancement to JSON that will also serialize methods. I have an object that acts as a collection of objects, and would like to serialize the methods of

3条回答
  •  礼貌的吻别
    2020-12-21 12:48

    I don't think serializing methods is ever a good idea. If you intend to run the code serverside, you open yourself to attacks. If you want to run it client side, you are better off just the local methods, possibly referencing the name of the method you are going to use in the serialized objects.

    I do believe though that "f = "+function() {} will yield you a to string version that you can eval:

    var test = "f = " + function() { alert("Hello"); };
    eval(test)
    

    And for good json handling, I would recommend prototype, which has great methods for serializing objects to json.

提交回复
热议问题