tbleckert
tbleckert

Reputation: 3801

Javascript strings and objects

In js can I call a function in an object 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

Upvotes: 1

Views: 68

Answers (2)

Klemen Slavič
Klemen Slavič

Reputation: 19841

var myObject = {
  myFunction: function() { return "Hooray!"; }
}

var methodName = "myFunction";

alert( myObject[methodName]() );

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630379

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).

Upvotes: 10

Related Questions