JavaScript call, apply and bind

All three functions are used to change the context of function. There is lot of confusion about these three functions. So I will try to explain the difference between these with simple example.

Call

Call is used to call the function with context (this) and arguments.

function sayHello(a,b) {
  console.log("argument a = " + a);
  console.log("argument b = " + b);
  alert("Hello " + this.name + "!");
}

If we directly call the sayHello function it will throw error as name is not available in functions context. Now lets call this function by changing its context and passing arguments.

// context to be passed to call function
var context = {
  name:'Mangesh'
}

// call sayHello with context and arguments
sayHello.call(context, 10, 20);

// Output -
// argument a = 10
// argument b = 20
// Hello Mangesh !

Points to be noted here –

  1. Context passed to call function is available as this in sayHello. So this.name is now defined in functions context.
  2. Arguments to sayHello are passed as comma separated

Apply

Apply is similar to call, the only difference is that apply takes array of arguments instead of comma separated arguments. You can remember it like –

Call – C for COMMA
Apply – A for ARRAY

Above example with apply will look like –

// context to be passed to apply function
var context = {
  name:'Mangesh'
}

// call sayHello with context and arguments
sayHello.apply(context, [10,20]);

// Output -
// argument a = 10
// argument b = 20
// Hello Mangesh !

Bind

Bind function instead of directly calling the sayHello function returns the instance of function bound to context passed.

// context to be passed to bind function
var context = {
  name:'Mangesh'
}

// bind context to sayHello
var boundSayHello = sayHello.bind(context);

// after bind, this = context
boundSayHello(10,20); 

// Output -
// argument a = 10
// argument b = 20
// Hello Mangesh !

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s