1

How do I load a javascript function from a variable name. For example:

var variable = 'world';

function helloworld()
{
 // blah
}

// I want to load helloword();
hello + variable + ();

How would I load helloworld() function like this?

1
  • 1
    Why don't you do hello(variable) instead? Commented Jan 10, 2013 at 17:29

2 Answers 2

7

If helloworld function is defined in global scope, then use:

window["hello" + variable]();
Sign up to request clarification or add additional context in comments.

1 Comment

@David It works if you change the scope from onLoad of MooTools: jsfiddle.net/k6FsU/1.
0

Depending on how many functions you have, you could do this:

var variable = "world"

var hello = {
  world : function() { /* Function contents */ },
  cat   : function() { /* Function contents */ },
  food  : function() { /* Function contents */ },
  …
}

hello[variable]();

Comments

Your Answer

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.