What I want is to create a function whose name will come from the content of one of my variables.
Example :
var myFunctionName = "tryAgain";`
[tryAgain]
|
|
|
function myFunctionName() {
alert('Try Again !');
};
mshell_lauren
5,2744 gold badges31 silver badges37 bronze badges
asked Mar 29, 2011 at 16:44
Sindar
11k7 gold badges34 silver badges45 bronze badges
4 Answers 4
To create a new function in the current context
this[myFunctionName] = function() {
// statements
}
answered Mar 29, 2011 at 16:48
harpo
43.5k15 gold badges102 silver badges134 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Although your question has been answered correctly already, I suggest to use an object that holds your functions, assuming that you generate more than one. The advantage is, that you can then iterate over all your generated functions and you put them into a namespace at the same time.
var funcs = {};
var name = 'test';
funcs[name] = function()
{
alert("Called a custom function");
};
funcs.test();
// Does the same funcs[name]();
answered Mar 29, 2011 at 16:53
Daff
44.4k9 gold badges108 silver badges122 bronze badges
Comments
window[myFunctionName] = function () {
alert('Try Again !'); };
Works in the global context.
answered Mar 29, 2011 at 16:48
HBP
16.1k6 gold badges30 silver badges34 bronze badges
Comments
eval("function "+myFunctionName+"(){alert('Try Again !');}");
I don't recommend this ;) But is another way you could do that.
answered Mar 29, 2011 at 16:51
Van Coding
24.6k25 gold badges94 silver badges138 bronze badges
Comments
lang-js