Naigel Naigel - 17 days ago 5
Javascript Question

save a function in localstorage

I'm working with some objects that contains a number of data to be displayed and manipulated from browser, and I want to save it in local storage.
In order to save objects I used JSON.stringify() so everything become text, and it works well

{
"bindingRef": [],
"primo": {
"name": "primo",
"modifiable": true,
"binded": false,
"isInteger": false,
"label": "Numero di Primi"
},
"secondo": {
"name": "secondo",
"modifiable": true,
"binded": false,
"isInteger": false,
"label": "Numero di Secondi"
}
}


Now I'm trying to save also a function by converting it to a string and then saveing it

JSON.stringify(myFunction.toString());


but the output is this

"savedFunction": "function () {\n\t\t\t\tvar tot = menu.primo.get() * 6 + menu.secondo.get() * 8 + menu.dolce.get() * 4;\n\t\t\t\tif (menu.sconto.get()) {\n\t\t\t\t\treturn tot * 0.90;\n\t\t\t\t} else {\n\t\t\t\t\treturn tot;\n\t\t\t\t}\n\t\t\t}"


Is it the correct way to save a function in local storage or is there a better way to do this? If this is the correct way, is there a way to simply remove any tabulation/indentation character or should I manipulate the string, for example using some regexp function?

Answer

Function in JS as in many functional languages are closures: they wrap inside them the content of the environment scope at the moment of definition, including ephemeral data like db or file handles.

It's not a good idea because this can lead to problems due to JSON deserialization behaviour, so you have to check what in the function is wrapped and what is self-defined.

See also this SO thread for further information.