A better way to create a function from a string is by using Function
:
var fn = Function("alert('hello there')");
fn();
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:
var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'
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:
You're pretty close.
//Create string representation of function
var s = "function test(){ alert(1); }";
//"Register" the function
eval(s);
//Call the function
test();
Here's a working fiddle.
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...
if (typeof String.prototype.parseFunction != 'function') {
String.prototype.parseFunction = function () {
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(this.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
examples of usage:
var func = 'function (a, b) { return a + b; }'.parseFunction();
alert(func(3,4));
func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction();
func();
here is jsfiddle
JavaScript
Function
var name = "foo";
// Implement it
var func = new Function("return function " + name + "(){ alert('hi there!'); };")();
// Test it
func();
// Next is TRUE
func.name === 'foo'
Source: http://marcosc.com/2012/03/dynamic-function-names-in-javascript/
eval
var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'
sjsClass
https://github.com/reduardo7/sjsClass
Class.extend('newClassName', {
__constructor: function() {
// ...
}
});
var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'
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