Tuesday, May 17, 2011

javascript dynamically call function by name

dynamically calling a function by name is easy in PHP:

class Person
{
    private $_category = 'human';
    public function getCategory() {
        return $this->_category;
    }
}

$p = new Person();
$method = 'getCategory';
echo $p->$method();

So how to dynamically call a function in javascript? let's see the code:

Person = {
    category : 'human',
    getCategory : function() {
        return this.category;
    }
};

var method = 'getCategory';
Person[method].apply(Person);

That is it! actually, it is the same question as how to access an object's property and method dynamically in javascript. As to the apply method, check my last blog : http://hengrui-li.blogspot.com/2011/05/javascript-callback-function-scope.html

Well, the example shows how to dynamically call an object's method by name in javascript. So how to dynamically call a global function by name in javascript? Easy as well. Remember that everything in javascript is actually a property of the global object? Check this code:

callMe = function() {
    alert('call me');
};

var method = 'callMe';

//in browser enviroment, window is the global object
window[method].apply();

No comments: