How can I serialize a function in JavaScript?

后端 未结 7 1139
Happy的楠姐
Happy的楠姐 2020-12-05 01:59

For example, say I have a function defined as follows:

function foo() {
  return \"Hello, serialized world!\";
}

I want to be able to seria

7条回答
  •  悲哀的现实
    2020-12-05 02:40

    Most browsers (Chrome, Safari, Firefox, possibly others) return the definition of functions from the .toString() method:

    > function foo() { return 42; }
    > foo.toString()
    "function foo() { return 42; }"
    

    Just be careful because native functions won't serialize properly. For example:

    > alert.toString()
    "function alert() { [native code] }"
    

提交回复
热议问题