In js can I call a function in an o开发者_运维百科bject from a string? Hm, I show you with an example:
var Object = {
callMe : function() { }
}
Object.callMe();
This I can do, but what if I want to do this:
var string = 'callMe';
Object.string();
Can I somehow do this? Maybe I'm just thinking wrong here
For this use bracket notation, like this:
var string = 'callMe';
Object[string]();
You can test it out here.
In JavaScript obj.thing
(dot notation) is accessing the same thing as obj["thing"]
(bracket notation).
var myObject = {
myFunction: function() { return "Hooray!"; }
}
var methodName = "myFunction";
alert( myObject[methodName]() );
精彩评论