简体   繁体   English

JavaScript动态函数名称

[英]JavaScript dynamic function name

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) ; 我要寻求帮助的问题是在这里尝试调用该函数: 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'; 编辑:我在这里传递了一个字符串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. 这就是为什么我必须使用字符串作为外部应用程序的起点。

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;

Access the functions using this syntax window[function_name]('para1'); 使用此语法window[function_name]('para1');访问函数。 window[function_name]('para1');

Your usage will be something like this 您的用法将是这样的

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

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. 我将使用window []并在尝试执行之前确保其功能,因为您无法控制传递的内容。

var f = window[cr['cmd1']];
if(typeof f==='function') {
  f(x);
}

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. 此代码将导致一个包含数字5的警报框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM