Creating functions from strings can be achieved without relying on the eval()
function.
var obj = {a:function(a,b){
return a+b;
}};
var serialized = JSON.stringify(obj, function(k,v){
//special handling for function types
if(typeof v === "function")
return v.toString();//converting functions to strings
return v;
});
/*output:
"{"a":"function (a,b){\n return a+b;\n }"}"
*/
Now, let's delve into the process of transforming a string back into a function using this method:
var compileFunction = function(str){
//extract parameters
var pstart = str.indexOf('('), pend = str.indexOf(')');
var params = str.substring(pstart+1, pend);
params = params.trim();
//extract function body
var bstart = str.indexOf('{'), bend = str.lastIndexOf('}');
var str = str.substring(bstart+1, bend);
return Function(params, str);
}
We can then utilize JSON.parse with a reviver function as shown below:
var revivedObj = JSON.parse(serialized, function(k,v){
// a basic check to identify function strings
if(typeof v === "string" && v.indexOf("function") !== -1)
return compileFunction(v);
return v;
});
//output:
revivedObj.a
function anonymous(a,b
/**/) {
return a+b;
}
revivedObj.a(1,2)
3