0

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

CHARLI
  • 27
  • 6
  • what's `Freq` and `meID`? That's not clear what exactly you're asking – GG. Apr 19 '16 at 19:59
  • http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string – izzy Apr 19 '16 at 20:00
  • You *can* do that, but you **probably shouldn't**. I'd advise you to explain why you want to do that and maybe get an answer for a better design. Also, you could benefit from studying JavaScript more thoroughly as it looks you lack some basic understanding (by the terms you use). – Amit Apr 19 '16 at 20:01
  • function custom values such as act(1, 2) – CHARLI Apr 19 '16 at 20:01
  • i have to use such way because i have multiple tabs and i must use separate functions for each tabs and this is easy way to do – CHARLI Apr 19 '16 at 20:04
  • Any time you find yourself needing to get a variable or function name from a string, you probably should be using an object to map names to values. You can make an object whose values are functions. – Barmar Apr 19 '16 at 20:25

3 Answers3

0

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.

Community
  • 1
  • 1
slessans
  • 677
  • 4
  • 16
0

There's nothing stopping you from re-declaring act as a function, you would just lose all references to the initially declared act from the point onward.

parrott-kevin
  • 118
  • 1
  • 7
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612