1

Say I have a function in javascript

var fn = function () {
        return 6 + 5;
};

and then I do

fn.toString();

which returns

"function () { return 6 + 5; }"

how can I turn this back into a function and eventually call it later on. I've tried eval as other people have said but this does not seem to be working for me. Any help would be much appreciated!!!

Lee Dennis
  • 95
  • 1
  • 1
  • 5

3 Answers3

1

You can give a name to the function, then you can call it. This should work

var fn = function () {
    return 6 + 5;
};
var stringFunc = fn.toString();

eval("var newfn = " + stringFunc);
console.log(newfn())

you can also execute it passing the parameters like this

console.log(eval("("+stringFunc+")()"))
jperelli
  • 6,988
  • 5
  • 50
  • 85
1

@LeeDennis just call fn(); instead of fn.toString(); the variable "fn" is the function you just need to add the parenthesis.

I console logged the outputs so you can see them.

//CODE

<!DOCTYPE html>
<html>
<head>
<script>
var fn = function () {
        return 6 + 5;
};
console.log(fn()); //returns 11
console.log(fn.toString()); //returns "function () { return 6 + 5; }"
</script>
</head>
<body>
</body>
</html>
Jordan Davis
  • 1,485
  • 7
  • 21
  • 40
1

Use eval():

fnString = 'function () { return 6 + 5; }';
fn = eval('(' + fnString + ')');
alert(fn());

Check this out:

JavaScript eval() "syntax error" on parsing a function string

Community
  • 1
  • 1
lintmouse
  • 5,079
  • 8
  • 38
  • 54