2

Possible Duplicate:
Javascript dynamic variable name

I'm trying to create a function in javascript that has a name dependent on a variable.

For instance:

var myFuncName = 'somethingWicked';
function myFuncName(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'

I can't seem to figure out a way to do it.... I tried to eval it, but then when I try and use the function at a later time it 'doesnt exist'.. or more exactly I get a ReferenceError that the function is undefined...

Any help would be appreciated.

Community
  • 1
  • 1
Aram Papazian
  • 2,281
  • 6
  • 36
  • 43

3 Answers3

4

You could assign your functions to an object and reference them like this:

var funcs = {};
var myFuncName = 'somethingWicked';
funcs[myFuncName] = function(){console.log('wicked');};
funcs.somethingWicked(); // consoles 'wicked'

Alternatively, you could keep them as globals, but you would still have to assign them through the window object:

var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
lbstr
  • 2,792
  • 17
  • 29
  • I don't think that this resolves, since `funcs.somethingWicked.name == ""` – Alisson Nunes Jul 19 '21 at 17:57
  • The solution should be this: ```var myFuncName = 'somethingWicked'; var funcs = { [myFuncName]: function(){console.log('wicked');} }; funcs.somethingWicked(); // consoles 'wicked' console.log(funcs.somethingWicked.name); // consoles 'somethingWicked'``` – Alisson Nunes Jul 19 '21 at 17:58
0
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
epascarello
  • 195,511
  • 20
  • 184
  • 225
0

Any time you have to create something that depends on a dynamic name for a variable you should be using a property of an object or an array member instead.

var myRelatedFunctions = {};
var myFuncName = 'somethingWicked';
myRelatedFunctions[myFuncName] = function (){console.log('wicked');};
myRelatedFunctions['somethingWicked']()
Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264