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,453
  • 6
  • 38
  • 45

3 Answers3

5

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,822
  • 18
  • 29
  • I don't think that this resolves, since `funcs.somethingWicked.name == ""` – Alynva 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'``` – Alynva Jul 19 '21 at 17:58
0
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
epascarello
  • 204,599
  • 20
  • 195
  • 236
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
  • 914,110
  • 126
  • 1,211
  • 1,335