Inverse operation for Javascript Function.toString ()

For a Javascript application, I need the user to be able to save the state of the object. This includes saving a set of user-defined functions that were previously created dynamically or through a graphical interface, and later loading these stored functions. Essentially, I need to serialize and non-sterilize functions.

Right now I am getting the serialized part using the Function.toString () method:

func.toString().replace('"', '\"').replace(/(\r)/g, ' ').replace(/(\n)/g, ' ').replace(/(\t)/g, ' ')

This gives me “serialized” functions similar to this beauty (note that the function is not called):

"function (someParameter) {this.someFunctionName(return 'something';}"

Non-serializing this is where I fight. My best solution for non-sterilizing functions:

var func = eval( 't =' +  so.actions[i].func);

Notice how I deliver the serialized function with t =before call eval(). I do not like to do this because it creates a global variable, but I cannot find a way to overcome it. When this is not added, I get the message "SyntaxError: Unexpected token (" When added var t =, eval () does not return a function, but undefined.

Are there alternative ways to "unserialize" an unnamed function?

PS: I am familiar with the security implications of using eval () for user input. For the foreseeable future, I am the only user of this software, so this is currently not a problem.

+5
source share
2 answers

Function, :

var func = Function("return " + so.actions[i].func)();

:

var func = eval("(function () { return " + so.actions[i].func + " })()");

, , - , , "" -.

, , , :

var func = eval("(" + so.actions[i].func + ")");
+6

:

eval('var func = ' + so.actions[i].func);
0

All Articles