oop – Javascript dynamically invoke object method from string-ThrowExceptions

Exception or error:

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();
How to solve:

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

foo[method]();

###

Properties of objects can be accessed through the array notation:

var method = "smile";
foo[method](); // will execute the method "smile"

###

method can be call with eval
eval("foo." + method + "()");
might not be very good way.

###

When we call a function inside an object, we need provide the name of the function as a String.

var obj = {talk: function(){ console.log('Hi') }};

obj['talk'](); //prints "Hi"
obj[talk]()// Does not work

Leave a Reply

Your email address will not be published. Required fields are marked *