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.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() { = || 'world';
    console.log('Hello, ' +;

//console log 'Hello world'

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

//bind the global object to "this" of the sayHello function,
//so console log 'Hello henry'

//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'

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]);, var1, var2); 

1 comment:

for IT the said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai