0

Does anybody know how to call a javascript function such as

function sampleCallback() {
      alert("hello");
}

from a string "sampleCallback()"?

I have a multidimensional array like so:

hintSlidesArray = [
                    [{ "element": "noelement" }, { "hintMessage": "Welcome"}, "callback": "sampleCallback" }],
                  ];

And would like to pass the callback string to it so that I can run it from where im reading the array.

2
  • You can call it with eval("sampleCallback()") Commented May 18, 2012 at 9:48
  • I've managed to use window[callback](); where callback is my method name. This is the most recommended setting and Eval is not! Commented May 18, 2012 at 9:52

3 Answers 3

4

Any global variables - including functions - are properties of the global object. In a browser environment this is window. So you can use the array subscript syntax to access the property you are looking for:

window[hintSlidesArray[0][2].callback]();

If you need to specify a value for this, you can use .call() or .apply():

window[hintSlidesArray[0][2].callback].call(value_for_this);

However, you should really consider storing the function instead of its name in your object. If the function is already defined in the current scope (or the global scope) when creating the object, this is as easy as removing the quotes from the function name.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use call or apply method. For example:

hintSlidesArray[0][2].callback.call(this)

1 Comment

hintSlidesArray[0][2].callback is a string. It doesn't have a call or apply method.
0

You can call the javascript function using window object:

var functionResult = window[myFunctionName];

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.