about 10 years ago
Hi, Generally, there are two methods to call a function from a string.
First solution is using **eval**. It is easy to use but generally real programmers avoid to use this.
Example 1 without arguments:
Example 2 with arguments:
- var funName = "executeMe";
- eval(funName)("First argument", "Second argument");
- function executeMe(arg1, arg2) {
- alert("Argument1 = " + arg1);
- alert("Argument12 = " + arg2);
- }
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
Now second one is to use **window** object which reference to current window.
example 1 without arguments:
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);
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.
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)