For example;
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
If this is the string, I want a function that's called fnc. And fnc();
pops alert screen.
eval("alert(1);")
doesnt solve my problem.
For example;
var s = "function test(){
alert(1);
}";
var fnc = aMethod(s);
If this is the string, I want a function that's called fnc. And fnc();
pops alert screen.
eval("alert(1);")
doesnt solve my problem.
You're pretty close.
Here's a working fiddle.
This technique may be ultimately equivalent to the eval method, but I wanted to add it, as it might be useful for some.
This is functionally like adding this <script> element to the end of your document, e.g.:
Yes, using
Function
is a great solution but we can go a bit further and prepare universal parser that parse string and convert it to real JavaScript function...examples of usage:
here is jsfiddle
Dynamic function names in
JavaScript
Using
Function
Source: http://marcosc.com/2012/03/dynamic-function-names-in-javascript/
Using
eval
Using
sjsClass
https://github.com/reduardo7/sjsClass
Example
A better way to create a function from a string is by using
Function
:This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.
Passing arguments is possible too:
I added a jsperf test for 4 different ways to create a function from string :
Using RegExp with Function class
var func = "function (a, b) { return a + b; }".parseFunction();
Using Function class with "return"
var func = new Function("return " + "function (a, b) { return a + b; }")();
Using official Function constructor
var func = new Function("a", "b", "return a + b;");
Using Eval
eval("var func = function (a, b) { return a + b; };");
http://jsben.ch/D2xTG
2 result samples: