Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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();
share|improve this question
add comment (requires an account with 50 reputation)

3 Answers

up vote 9 down vote accepted

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

foo[method]();
share|improve this answer
Thanks guys, that was so easy I totally overlooked it. Was already searching for some magical functions and tricks. – Mikulas Dite Mar 24 '12 at 20:13
add comment (requires an account with 50 reputation)

Properties of objects can be accessed through the array notation:

var method = "smile";
foo[method](); // will execute the method "smile"
share|improve this answer
add comment (requires an account with 50 reputation)

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

share|improve this answer
i had a nagging feeling there was something wrong with evil eval.. – hakovala Mar 24 '12 at 21:01
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.