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

后端 未结 7 1552
温柔的废话
温柔的废话 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:44

    There is no right way to do this, because its not generally a good idea.

    HOWEVER, if you want to do it anyways you can simply extend the prototype of Function with a .toJSON method.

    Function.prototype.toJSON = function(){ return this.toString(); }
    

    Then you can simply use JSON.stringify and functions will be serialized as strings.

    Its generally a not good idea in most cases. There are very few circumstances where you want to do this and even then, there is probably a better way.

提交回复
热议问题