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
    • 777
    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:

    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

    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:

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: