0

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

4 Answers 4

4

To create a new function in the current context

this[myFunctionName] = function() {
 // statements
}
answered Mar 29, 2011 at 16:48
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1
window[myFunctionName] = function () {
 alert('Try Again !'); };

Works in the global context.

answered Mar 29, 2011 at 16:48

Comments

0
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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.