开发者

Javascript strings and objects

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]() );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜