Hi,
Generally, there are two methods to call a function from a string.
- Using eval.
- Using window object.
First solution is using **eval**. It is easy to use but generally real programmers avoid to use this.
Example 1 without arguments:
var funName = "executeMe";
eval(funName)();
function executeMe() {
alert('executeMe')
}
Example 2 with arguments:
var funName = "executeMe";
eval(funName)("First argument", "Second argument");
function executeMe(arg1, arg2) {
alert("Argument1 = " + arg1);
alert("Argument12 = " + arg2);
}
But there are several issues with **eval** like
- Security issues: It can be injected by third party commands or user input.
- Hard to debug: You will have no line numbers.
Now second one is to use **window** object which reference to current window.
example 1 without arguments:
function executeMe() {
alert('executeMe');
}
var funName = "executeMe";
var fn = window[funName]
if (typeof fn === "function") fn();
Example 2 with arguments:
function executeMe(arg1, arg2, arg3) {
alert("Argument1 = " + arg1);
alert("Argument2 = " + arg2);
alert("Argument3 = " + arg3);
}
var funName = "executeMe";
var fnParams = [1, 2, 3];
var fn = window[funName]
if (typeof fn === "function") fn.apply(null, fnParams);
The second solution is better than using eval as it is safer, less chances of errors, easy to debug and it will execute faster.
0 Comment(s)