Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Calling JavaScript function from String

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 216
    Comment on it

    Sometimes, you may need to call a method at runtime. If you know the name of the function you can invoke it as a string. You can call a function as a string. You are basically achieving eval of javascript indirectly.

     

    Lets say, there is a function someFunction(), that you want to call in run-time, you can use the below code snippet for the same.


    For ex:
     

    var strFun = "someFunction";
    
    var strParam = "This is a parameter for the function";
    
    // creating the function
    var fn = window[strFun];
    
    fn(strParam);
    
    function someFunction(param) {
        console.log(param1);
    }
    
    /**
    *
    Result: This is a parameter for the function
    */
    
    

     

 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: