<!-- language: lang-js -->
function foo() {
alert('native function');
return 'Serialised function!';
}
## Serializing
<!-- language: lang-js -->
var storedFunction = foo.toString();
## Deserializing
<!-- language: lang-js -->
var actualFunction = new Function('return ' + foo.toString())()
You should serialize and deserialize your functions like this, because you can't directly serialize them to JSON
foo.toString() will be string version of the function foo
"function foo() { ... return 'Serialised function!';}"
But new Function takes the body of a function and not the function itself.
Simple demo:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var sum = new Function('a', 'b', 'return a + b');
console.log(sum(2, 6));
// expected output: 8
<!-- end snippet -->
<!-- language: lang-js -->
function foo() {
alert('native function');
return 'Hello, serialised world!';
}
## Serializing
<!-- language: lang-js -->
var storedFunction = foo.toString();
## Deserializing
<!-- language: lang-js -->
var actualFunction = new Function('return ' + foo.toString())()
### Explanation
foo.toString() will be string version of the function foo
"function foo() { ... return 'Hello, serialised world!';}"
But `new Function` takes the body of a function and not the function itself.
See [MDN: Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function)
So we can create a function that returns us back this function and assign it to some variable.
"return function foo() { ... return 'Hello, serialised world!';}"
So now when we pass this string to the constructor we get a function and we immediately execute it to get back our original function. :)