简体   繁体   中英

how to use var value name as function name in JavaScript

Hi guys can i use value as a function name in JavaScript? 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!! so i need to know how i can do that? thanks to all

You can use window[act](Freq, meId)

Thanks Justin Niessner for pointing out this will only work if act is defined in the global scope. You could use eval , however, this is generally considered to be very unsafe.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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