Javascript dynamically calls an object method from a string

Is it possible to dynamically call an object method with a method name as a string? I would suggest that this is so:

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(); 
+67
javascript methods oop dynamic invoke
Mar 24 2018-12-12T00:
source share
3 answers

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

 foo[method](); 
+158
Mar 24 '12 at 19:55
source share

Access to the properties of objects can be obtained through array notation:

 var method = "smile"; foo[method](); // will execute the method "smile" 
+25
Mar 24 '12 at 19:55
source share

the method can be called with eval eval("foo." + method + "()"); may not be a very good way.

-one
Mar 24 2018-12-12T00:
source share



All Articles