使用 JavaScript 变量作为函数名?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3619046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use JavaScript variable as function name?
提问by Alex Pliutau
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
谢谢
采纳答案by SLaks
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 keyvariable (or parameter).
但是,由于 Javascript 函数通过引用捕获变量,您的代码将无法按预期工作。
您需要在单独的函数内定义内部函数,以便每个函数都获得一个单独的key变量(或参数)。
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 createDialogand updateDialog.
In a normal function call, the thiskeyword refers to the global namespace (typically the windowobject).
这将创建名为createDialog和 的全局函数updateDialog。
在正常的函数调用中,this关键字指的是全局命名空间(通常是window对象)。
回答by RoToRa
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:
window[ actions[key] + "Dialog" ] = function(){ ... }
回答by aularon
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();
现在您可以将其称为window[funcName]();,window['varfuncname']();或varfuncname();
回答by Gooseus
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”变量将引用文档,而不是窗口。
回答by Neall
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 中,函数传递有点麻烦。在 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:
您打算如何稍后调用这些函数?我猜你已经将这些函数名称硬编码到 HTML 的“onclick”属性中。通过on*属性将JavaScript 硬编码到 HTML 中是一个坏主意。如果这就是你所做的,你必须在全局范围内创建变量(最好避免另一种做法)。在浏览器中,全局对象是window。如果您在 上定义属性window,则该函数将在全局范围内可用:
$(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 onclickattributes in your HTML that match up with the function names you're creating.
这假设onclick您的 HTML 中有与您正在创建的函数名称相匹配的属性。
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 更小更干净。

