How can I serialize a function in JavaScript?

Akash Gupta picture Akash Gupta · Sep 13, 2011 · Viewed 24.7k times · Source

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

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

I want to be able to serialize that function and store it using localStorage. How can I go about doing that?

Answer

David Wolever picture David Wolever · Sep 13, 2011

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