Call a method of object with string in JavaScript

var call_user_func = function(obj, method) {
    return eval('obj.' + method).apply(obj, Array.prototype.slice.call(arguments, 2));
}
var test1 = {
    method1: function(arg1, arg2, arg3) {
        return alert(arg1 + arg2 + arg3);
    }
}
call_user_func(test1, 'method1', 1, 2, 3);

It works on Firefox3, Safari4, IE6.

This entry was posted in Uncategorized. Bookmark the permalink. Trackbacks are closed, but you can post a comment.

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

  • About

    I'm Nobu, a web developer living in Mountain View, CA. Feel free to comment on any posts. I'm also tweeting on twitter.

  • Archives

  • Recent Posts