Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 238
Mikulas Dite Avatar asked Mar 24 '12 19:03

Mikulas Dite


1 Answers

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

foo[method](); 
like image 184
Karoly Horvath Avatar answered Sep 23 '22 17:09

Karoly Horvath