Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I serialize a function in JavaScript?

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?

like image 597
Akash Gupta Avatar asked Sep 13 '11 00:09

Akash Gupta


People also ask

Can functions be serialized in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .

Can functions be serialized?

Capturing modules in a JavaScript function Because a module is just a normal JavaScript value, it is possible to serialize it just like any other value.

What is serialize () in JavaScript?

The serialize() method creates a URL encoded text string by serializing form values. You can select one or more form elements (like input and/or text area), or the form element itself. The serialized values can be used in the URL query string when making an AJAX request.

Can JSON serialize functions?

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.


1 Answers

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] }" 
like image 88
David Wolever Avatar answered Sep 23 '22 07:09

David Wolever