Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to call a function from string in Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 817
    Comment on it

    Hi, Generally, there are two methods to call a function from a string.

    1. Using eval.
    2. 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:

    1. var funName = "executeMe";
    2. eval(funName)();
    3. function executeMe() {
    4. alert('executeMe')
    5. }

    Example 2 with arguments:

    1. var funName = "executeMe";
    2. eval(funName)("First argument", "Second argument");
    3. function executeMe(arg1, arg2) {
    4. alert("Argument1 = " + arg1);
    5. alert("Argument12 = " + arg2);
    6. }

    But there are several issues with **eval** like

    1. Security issues: It can be injected by third party commands or user input.
    2. 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:

    1. function executeMe() {
    2. alert('executeMe');
    3. }
    4. var funName = "executeMe";
    5. var fn = window[funName]
    6. if (typeof fn === "function") fn();

    Example 2 with arguments:

    1. function executeMe(arg1, arg2, arg3) {
    2. alert("Argument1 = " + arg1);
    3. alert("Argument2 = " + arg2);
    4. alert("Argument3 = " + arg3);
    5. }
    6. var funName = "executeMe";
    7. var fnParams = [1, 2, 3];
    8. var fn = window[funName]
    9. 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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: