How can I serialize a function in JavaScript?

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] }"

Leave a Comment