使用JavaScript变量作为函数名?

时间:2022-07-06 00:37:21

I have the following code in Javascript:

我在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');
                    }
                }
            });
        };
    }
});

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.

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

Thank you

谢谢

5 个解决方案

#1


6  

Like this:

喜欢这个:

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

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).

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

For example:

例如:

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() { ... };
}

You can use it like this:

你可以像这样使用它:

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]);
}

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).

这将创建名为createDialog和updateDialog的全局函数。在普通函数调用中,this关键字引用全局命名空间(通常是窗口对象)。

#2


2  

You'll need a reference to the scope object in which you want to create the functions. If it's the global scope you can use window:

您需要对要在其中创建函数的范围对象的引用。如果它是全局范围,您可以使用窗口:

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

#3


0  

javascript global scope is window, so you can write:

javascript全局范围是窗口,所以你可以写:

var funcName='varfuncname';
    window[funcName]=function() {
    alert('HI!');
}

Now you can call it as window[funcName]();, window['varfuncname'](); or varfuncname();

现在你可以把它称为窗口[funcName]();, window ['varfuncname']();或varfuncname();

#4


0  

You need to combine SLaks' and RoToRa's answers:

你需要结合SLaks和RoToRa的答案:

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

for (var i = 0; i < actionNames.length; i++) {
    window[ actionNames[i] + 'Dialog' ] = function() {
        $('#'+ actionNames[i] +'dialog').dialog('destroy');
        $('#'+ actionNames[i] +'dialog').dialog({
            resizable: false,
            height:600,
            width:400,
            modal: true,
            buttons: {
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });
    }
}

Since you're running this in the document ready event handler, the "this" variable would refer to the document, not the window.

由于您在文档就绪事件处理程序中运行它,因此“this”变量将引用文档,而不是窗口。

#5


0  

I think you're trying to do something that you don't need to do in JavaScript. In PHP, function passing is a bit of a kludge. In JavaScript it is elegant and painless.

我想你正在尝试做一些你不需要在JavaScript中做的事情。在PHP中,函数传递有点像kludge。在JavaScript中它优雅而无痛。

How are you planning on calling these functions later? I'm guessing that you have these function names hard-coded into your HTML in the 'onclick' attributes. Hard-coding JavaScript into your HTML via the on* attributes is a bad idea. If that's what you're doing, you have to create variables in the global scope (another practice best avoided). In the browser, the global object is window. If you define a property on window, the function will be available globally:

您打算如何在以后调用这些函数?我猜你在'onclick'属性中将这些函数名称硬编码到你的HTML中。通过on *属性将JavaScript硬编码到HTML中是一个坏主意。如果这就是你正在做的事情,你必须在全局范围内创建变量(最好避免使用另一种做法)。在浏览器中,全局对象是窗口。如果在窗口上定义属性,则该函数将全局可用:

$(document).ready(function() {
  var myNames = [
    'create',
    'destroy'
  ];
  for (var i = 0; i < myNames.length; i++) {
    window[myNames[i] + 'Dialog'] = function() {
      alert('Hello');
    };
  }
});

This assumes that you have onclick attributes in your HTML that match up with the function names you're creating.

这假设您在HTML中具有与您正在创建的函数名称匹配的onclick属性。

A better way to do this would be to just create the functions as you bind them to the events, never even assigning them to variables:

更好的方法是在将事件绑定到事件时创建函数,甚至不将它们分配给变量:

$(document).ready(function() {
  $('#createdialog, #destroydialog').each(function() {
    $(this).click(function() {
      alert('Hello');
    });
  });
});

This will make both your JavaScript and your HTML smaller and cleaner.

这将使您的JavaScript和HTML更小更清晰。

#1


6  

Like this:

喜欢这个:

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

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).

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

For example:

例如:

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() { ... };
}

You can use it like this:

你可以像这样使用它:

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]);
}

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).

这将创建名为createDialog和updateDialog的全局函数。在普通函数调用中,this关键字引用全局命名空间(通常是窗口对象)。

#2


2  

You'll need a reference to the scope object in which you want to create the functions. If it's the global scope you can use window:

您需要对要在其中创建函数的范围对象的引用。如果它是全局范围,您可以使用窗口:

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

#3


0  

javascript global scope is window, so you can write:

javascript全局范围是窗口,所以你可以写:

var funcName='varfuncname';
    window[funcName]=function() {
    alert('HI!');
}

Now you can call it as window[funcName]();, window['varfuncname'](); or varfuncname();

现在你可以把它称为窗口[funcName]();, window ['varfuncname']();或varfuncname();

#4


0  

You need to combine SLaks' and RoToRa's answers:

你需要结合SLaks和RoToRa的答案:

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

for (var i = 0; i < actionNames.length; i++) {
    window[ actionNames[i] + 'Dialog' ] = function() {
        $('#'+ actionNames[i] +'dialog').dialog('destroy');
        $('#'+ actionNames[i] +'dialog').dialog({
            resizable: false,
            height:600,
            width:400,
            modal: true,
            buttons: {
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });
    }
}

Since you're running this in the document ready event handler, the "this" variable would refer to the document, not the window.

由于您在文档就绪事件处理程序中运行它,因此“this”变量将引用文档,而不是窗口。

#5


0  

I think you're trying to do something that you don't need to do in JavaScript. In PHP, function passing is a bit of a kludge. In JavaScript it is elegant and painless.

我想你正在尝试做一些你不需要在JavaScript中做的事情。在PHP中,函数传递有点像kludge。在JavaScript中它优雅而无痛。

How are you planning on calling these functions later? I'm guessing that you have these function names hard-coded into your HTML in the 'onclick' attributes. Hard-coding JavaScript into your HTML via the on* attributes is a bad idea. If that's what you're doing, you have to create variables in the global scope (another practice best avoided). In the browser, the global object is window. If you define a property on window, the function will be available globally:

您打算如何在以后调用这些函数?我猜你在'onclick'属性中将这些函数名称硬编码到你的HTML中。通过on *属性将JavaScript硬编码到HTML中是一个坏主意。如果这就是你正在做的事情,你必须在全局范围内创建变量(最好避免使用另一种做法)。在浏览器中,全局对象是窗口。如果在窗口上定义属性,则该函数将全局可用:

$(document).ready(function() {
  var myNames = [
    'create',
    'destroy'
  ];
  for (var i = 0; i < myNames.length; i++) {
    window[myNames[i] + 'Dialog'] = function() {
      alert('Hello');
    };
  }
});

This assumes that you have onclick attributes in your HTML that match up with the function names you're creating.

这假设您在HTML中具有与您正在创建的函数名称匹配的onclick属性。

A better way to do this would be to just create the functions as you bind them to the events, never even assigning them to variables:

更好的方法是在将事件绑定到事件时创建函数,甚至不将它们分配给变量:

$(document).ready(function() {
  $('#createdialog, #destroydialog').each(function() {
    $(this).click(function() {
      alert('Hello');
    });
  });
});

This will make both your JavaScript and your HTML smaller and cleaner.

这将使您的JavaScript和HTML更小更清晰。