11

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();
}
8
  • 1
    why would you do this? eval() Commented Jun 5, 2012 at 16:34
  • 1
    You can use eval() to execute Javascript in a string, but this is normally considered a Very Bad Practice. It isn't making sense to me why you would want to store JQuery event functions in a MySql table. Maybe you should rethink what you are trying to do. Commented Jun 5, 2012 at 16:36
  • @js1568. It doesn't have to be eval. Commented Jun 5, 2012 at 16:36
  • My Plan was to capture the state of a page then save this information then restore it at a later date. Commented Jun 5, 2012 at 16:38
  • @Robert. Then, it's a bad way of doing it... Commented Jun 5, 2012 at 16:38

3 Answers 3

22
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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer. I was just looking for a quick way of saving this information but if its such bad practice I will make sure to do it this way.
My answer does not require to store parameters in any DB
4

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)

Comments

1

Javascript provides the new- keyword for functions

var foo = new Function("arg", ... , "<implementation string>");

see here for example... http://www.permadi.com/tutorial/jsFunc/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.