Reputation: 1879
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.
Upvotes: 0
Views: 483
Reputation: 4373
You can call the javascript function using window object:
var functionResult = window[myFunctionName];
Upvotes: 0
Reputation: 318748
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.
Upvotes: 4