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

后端 未结 7 1560
温柔的废话
温柔的废话 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条回答
  •  Happy的楠姐
    2020-12-17 02:49

    Changing the prototype of the object is a half thought I have.

    You've got your library like

    library = {
      "myObj" : {"name" : "myObj", "type" : "myType", "function" : function () { } } //, etc
    }
    

    You've got an object (let's call it theObj) that you know is a myObj (due to a string maybe? property?)

    theObj.__proto__ = library["myObj"];
    

    That way you can execute

    theObj.function(...);
    

    jsfiddle example (it's rough!). Also, be careful with proto, it's deprecated (1) (2)

    As to serializing the functions, can you get them in using a script tag that points to something serverside that slurps them from the db and returns the js? Just include them inline as you render the page (in a script block)? Or, if all else fails, eval should work, as long as you know that the functions you've got stored in the database are clean and safe.

提交回复
热议问题