May 2, 2012

JavaScript dynamic function name

Question by John R

I need to dynamically assign the name of a function to an element of an associative array. This is my attempt which does not work. The problem I am asking for help with is here where I try to call the function: cr['cmd1'](x);

<!DOCTYPE html>

<html>
<head>
    <script type="text/javascript">
        var cr =[];
        var x = 5;
        cr['cmd1'] ='foo';
        var msg = cr['cmd1'](x);  
        alert(msg);

        function foo(y){
            return y;
        }
    </script>
</head>
<body>
</body>
</html>

Edit: I being passed a string here cr['cmd1'] ='foo'; that I cannot control. That is why I have to work with a string as a starting point from an external application.

Answer by Starx

Access the functions using this syntax window[function_name]('para1');

Your usage will be something like this

var msg = window[cr['cmd1']](x);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!