Turning JSON strings into objects with methods

前端 未结 8 505
抹茶落季
抹茶落季 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:11

    From ECMAScript 6 onwards you can just do:

    Object.assign(new Obj(), JSON.parse(rawJsonString))
    

    Note: You create a new empty object of the defined type first and then override its properties with the parsed JSON. Not the other way around.

    The methods define behaviour and contain no variable data. They are "stored" as your code. So you don't actually have to store them in the database.

提交回复
热议问题