javascriptoopdynamicmethodsinvoke

Javascript dynamically invoke object method from string


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

Solution

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

    foo[method]();