简体   繁体   English

如何在JavaScript中使用var值名称作为函数名称

[英]how to use var value name as function name in JavaScript

Hi guys can i use value as a function name in JavaScript? 大家好,我可以在JavaScript中使用value作为函数名称吗? i have some functions with same name input values such as: 我有一些具有相同名称输入值的函数,例如:

var ta = $('li.ramin.active').attr("id");
var act = $('input[name="'+ta+'_acceptdeny"]:checked').val();


act(Freq, meID);  // my question is

in this way i have error "Uncaught TypeError: act is not a function" yes i know act is not a function but i want to use var act value as function name!! 这样我有错误“未捕获的TypeError:行为不是函数”是的,我知道行为不是函数,但是我想使用var act值作为函数名! so i need to know how i can do that? 所以我需要知道我该怎么做? thanks to all 谢谢大家

You can use window[act](Freq, meId) 您可以使用window[act](Freq, meId)

Thanks Justin Niessner for pointing out this will only work if act is defined in the global scope. 感谢Justin Niessner指出,只有在全局范围内定义了act ,此方法才有效。 You could use eval , however, this is generally considered to be very unsafe. 您可以使用eval ,但是,通常认为这是非常不安全的。

没有什么可以阻止您将行为重新声明为函数,从此以后,您将丢失对初始声明的行为的所有引用。

Instead of using the value as a function name, put the functions into an object, and use the value as the key to the object. 不要将值用作函数名,而是将函数放入对象中,然后将值用作对象的键。

var myFunctions = {
    'func1': function() { .... },
    'func2': function() { .... },
    // and so on
};

var ta = $('li.ramin.active').attr("id");
var act = $('input[name="'+ta+'_acceptdeny"]:checked').val();

myFunctions[act](Freq, meID);

This is better because you can't accidentally call a function that was not intended to be used by the application, it can only call functions in the myFunctions object. 这样比较好,因为您不能偶然调用应用程序不打算使用的函数,它只能调用myFunctions对象中的函数。

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

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