0

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.

John R
  • 2,920
  • 13
  • 48
  • 62
  • What doesn't work? What's the error? What are you expecting the alert results to be? – KP. May 02 '12 at 18:28

4 Answers4

5

If you want to store it as a function, pass the function directly. Otherwise, if you just want to store it as a string, then you can use the quotes.

Change:

cr['cmd1'] ='foo';

To:

cr['cmd1'] = foo;
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
5

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

Your usage will be something like this

var msg = window[cr['cmd1']](x);
Starx
  • 77,474
  • 47
  • 185
  • 261
1

I would use window[] and make sure its a function before trying to execute it since you don't have control over what is passed.

var f = window[cr['cmd1']];
if(typeof f==='function') {
  f(x);
}
Tim
  • 397
  • 2
  • 4
0

What you are doing there is assigning a function to an array. A more common pattern that you are probably trying to do is to call a function on an object with the array notation.

    <script type="text/javascript">
        var cr = {};
        cr.cmd1 = function foo(y){
            return y;
        };
        var x = 5;
        var msg = cr['cmd1'](x);  
        alert(msg);
    </script>

This code results in an alert box that contains the number 5.

James
  • 710
  • 6
  • 19