Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string (was a function) back to function in Javascript

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();
}
like image 756
Robert Avatar asked Jun 05 '12 16:06

Robert


2 Answers

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.

like image 138
gdoron is supporting Monica Avatar answered Sep 20 '22 17:09

gdoron is supporting Monica


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)
like image 20
Fernando Carvajal Avatar answered Sep 20 '22 17:09

Fernando Carvajal