I have this function below as a string. How would I convert it back into a function? I am pulling event handlers from JQuery events and I want to store them as string then convert them back because they will be saved in mySQL
function () {
if (!GActiveClick) {
return;
}
SaveProduct();
}
var func = new Function(theFunctionString);
func();
MDN:
new Function ([arg1[, arg2[, ... argN]],] functionBody)
Parameters
arg1, arg2, ... argN
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".functionBody
A string containing the JavaScript statements comprising the function definition.
Update:
All this a very bad practice!
You should have a generic function that get parameters that build what you want. The only thing that change are the parameters. Store those parameters in the DB you have.
Use the return
when using new Function()
and execute it, like this
new Function('return ' + fn_string)();
Example:
function hackerAll(a, b) {
var result = a*b
return result
}
class Doggy{
method1(){
return 123123*342343
}
}
var fn_string = hackerAll.toString()
var back_to_fn = new Function(`return ${fn_string}`)() //This restore the function with name, params and all, even es7 class works
var class_string = Doggy.toString()
var back_to_class = new Function(`return ${class_string}`)()
console.log('fn as it', hackerAll)
console.log('fn string', fn_string)
console.log('restored fn', back_to_fn)
console.log('restored class', back_to_class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With