Dynamically generating a function name based on a variable
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]
|
开发者_如何学Go |
|
function myFunctionName() {
alert('Try Again !');
};
To create a new function in the current context
this[myFunctionName] = function() {
// statements
}
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]();
window[myFunctionName] = function () {
alert('Try Again !'); };
Works in the global context.
eval("function "+myFunctionName+"(){alert('Try Again !');}");
I don't recommend this ;) But is another way you could do that.
精彩评论