Month: May 2013

Call and apply Invocation Pattern in JavaScript

So I think most of the guys have confusion about call and apply invocation pattern in Javascript. Let me clear all your confusion. First I will talk about apply invocation pattern which I love the most .. 

Apply Invocation Pattern:-

As Javascript is functional object oriented language , Here functions can have methods. The apply invocation pattern allow us to create an array of arguments to use to invoke the function. The apply invocation pattern takes two parameters :-

  1. The value that should be bounded to this pointer
  2. Array of parameters

For example:-

var add=function(a,b){

return a+b;

}

var array=[2,3]

add.apply(null,array);

In above example this pointer is bound to null because here the function add is not an object, so it is not needed. Now Let me show you the way we can change ‘this’ pointer.

var display=function(){

alert(this.property);

}

var greeting={

property:”Hi Good Morning”

}

display.apply(greeting);

 

Here the value of the ‘this’ pointer is bound to an object called ‘greeeting’. So we can explicitly change the value of ‘this’ pointer here.

 

Call Invocation Pattern:-

So here we can’t create array of parameters. We have to pass all the parameters. So call invocation pattern has a signature like this:-

function.call(this pointer,parameter1,parameter2,…)

For Example:-

var display=function(obj){

alert(this.property);

}

var person={

property:”Me”

}

display.call(person);

Here the value of this parameter is bound to the person object. So lets take another example of call invocation pattern.

var display=function(text1,text2){

alert(text1+”,”+text2+”,”+this.name1+”,”+this.name2);

}

var person={

name1:”Me”,

name2:”Awesome”

}

display.call(person,”Hi”,”Bye”);

So the output for the above code will be Hi,Bye,Me,Awesome. 

So this is all about call and apply invocation patterns in javascript. The major difference is that apply invocation pattern allow us to create an array of parameters and pass it as an argument. Thats why I love apply pattern the most.