1

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

2 Answers 2

10

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

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

Comments

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

var methodName = "myFunction";

alert( myObject[methodName]() );

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.