Wednesday, May 25, 2011

javascript apply function (function application)

In javascript, when a function is called/invoked, it is actually applied. Calling a function is actually applying a set of arguments to a function. This concept exists in some purely functional programming languages as well.(Now who is saying javascript is an OOP language?)

function sayHiTo(who) {
   console.log('Hi, ' + who);
}

//you will have same result
sayHi('henry');
sayHi.apply(null, ['henry']);

apply() takes two parameters: the first one is an object to bind to "this" inside of
the function, the second is an array or parameters. If the first parameter is null, then "this"
points to the global object. 

So, let's do some interesting test

function sayHelloTo() {
    this.name = this.name || 'world';
    console.log('Hello, ' + this.name);
}

//console log 'Hello world'
sayHelloTo();

//define a global name variable
var name = 'henry';

//bind the global object to "this" of the sayHello function,
//so console log 'Hello henry'
sayHelloTo.apply();

//define a person object with name property
var person = {
   name : 'stranger'
}
//bind person object to "this" of the sayHello function
//so console log 'Hello stranger'
sayHelloTo.apply(person);

In addition to apply(), javascript function also has a call() method. call() is doing the same thing as apply() with only one difference: the second parameter of apply() should be an array of arguments, while call() takes arguments separated by comma. For example:

//both do the same job
func.apply(object, [var1, var2]);
func.call(object, var1, var2); 


No comments: