Javascript dynamically invoke object method from string

Mikulas Dite picture Mikulas Dite · Mar 24, 2012 · Viewed 61.6k times · Source

Can I dynamically call an object method having the method name as a string? I would imagine it like this:

var FooClass = function() {
    this.smile = function() {};
}

var method = "smile";
var foo = new FooClass();

// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();

Answer

Karoly Horvath picture Karoly Horvath · Mar 24, 2012

if the name of the property is stored in a variable, use []

foo[method]();