使用 JavaScript 变量作为函数名? [英] Use JavaScript variable as function name?

查看:53
本文介绍了使用 JavaScript 变量作为函数名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Javascript 中有以下代码:

I have the following code in Javascript:

jQuery(document).ready(function(){
    var actions = new Object();
    var actions;
    actions[0] = 'create';
    actions[1] = 'update';
    for (key in actions) {
        // Dialogs
        var actions[key]+Dialog = function(){
            $('#'+actions[key]+'dialog').dialog('destroy');
            $('#'+actions[key]+'dialog').dialog({
                resizable: false,
                height:600,
                width:400,
                modal: true,
                buttons: {
                    Cancel: function() {
                        $(this).dialog('close');
                    }
                }
            });
        };
    }
});

我想在循环中创建 2 个函数(createDialog 和 updateDialog).我怎样才能做到这一点?在 PHP 中有非常简单的 $$var.但是我不知道如何在 JS 中使可变变量.

I want to create 2 functions in loop(createDialog and updateDialog). How can i do this? In PHP there is very simple $$var. But how make variable variable in JS I don't know.

谢谢

推荐答案

像这样:

actions[key + "Dialog"] = function () { ... };

但是,由于 Javascript 函数通过引用捕获变量,您的代码将无法按预期工作.
您需要在单独的函数中定义内部函数,以便每个函数都获得一个单独的 key 变量(或参数).

However, since Javascript functions capture variables by reference, your code will not work as intended.
You need to define the inner function inside of a separate function so that each one gets a separate key variable (or parameter).

例如:

var actionNames = [ 'create', 'update' ];   //This creates an array with two items
var Dialog = { };    //This creates an empty object

for (var i = 0; i < actionNames.length; i++) {
    Dialog[actionNames[i]] = createAction(actionNames[i]);
}

function createAction(key) {
    return function() { ... };
}

你可以这样使用它:

Dialog.create(...);

编辑

您正试图使用​​多个与对话框相关的函数来污染全局命名空间.
这是一个坏主意;最好将您的函数组织到命名空间中.

EDIT

You are trying to pollute the global namespace with multiple dialog-related functions.
This is a bad idea; it's better to organize your functions into namespace.

如果你真的想污染全局命名空间,你可以这样做:

If you really want to polute the global namespace, you can do it like this:

var actionNames = [ 'create', 'update' ];   //This creates an array with two items

for (var i = 0; i < actionNames.length; i++) {
    this[actionNames[i] + 'Dialog'] = createAction(actionNames[i]);
}

这将创建名为 createDialogupdateDialog 的全局函数.
在正常的函数调用中,this 关键字指的是全局命名空间(通常是 window 对象).

This will create to global functions called createDialog and updateDialog.
In a normal function call, the this keyword refers to the global namespace (typically the window object).

这篇关于使用 JavaScript 变量作为函数名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆