What is the correct way to “serialize” functions in javascript for later use

后端 未结 7 1564
温柔的废话
温柔的废话 2020-12-17 02:08

I have a \"library\" of objects that I want to load on the fly from a database. Each object comes with its own special functions that are called at specific times depending

7条回答
  •  情话喂你
    2020-12-17 02:30

    Just use eval to recreate the function after loading it as a string. So if you deserialize an object myObj from JSON, and you have a property:

    myObj = {
        ....
        function: "function() { ... }"
    }
    

    you can very easily turn it to a real function:

    eval("myObj.func = " + myObj.func);
    

    http://jsfiddle.net/kceTr/

    Oh - I am not sure if that was an edit or I missed it before - but re: eval.

    Eval is a tool. You want to store a function in a database. It really doesn't make much difference if you have to "eval" to turn it into code, or there was some other magic way to do it: if someone can change the data in your DB, then they can change a function.

    If you need to store a function, then eval is your tool. It's not "bad" by nature, it's bad because it's easy to misuse. Whether you use it well or not is up to you.

    Remember anything running on the client is still just running on the client. There's nothing a malicious person could do with eval, that they couldn't do with the Chrome debugger a lot more easily. Anyone can always run any code they want on the client, it's up to your server to decide how to handle what it receives. There's nothing safe on the client in the first place...

提交回复
热议问题