Understanding .call, .apply, and .bind!

Quick guide to mastering ‘this’ binding and usage in javascript.

Call, apply, and bind?!

The ‘this’ keyword is an extremely powerful tool for programmers. Tracking and using ‘this’ can be quite confusing at times. Luckily there are methods to help keep ‘this’ simple. On the other hand understanding the methods .call, .apply, and .bind can be just as confusing.

Below we have an object and a function using the ‘this’ keyword to change the color property of an object. Imagine the car has been replaced with a black Honda, how would one update the car object using updateVehicle (without modifying it)?

var car = { model: 'Ford', color: 'Red' }
function updateVehicle (model, color) {
this.model = model;
this.color = color;

Using Call and Apply

updateVehicle.call(car, 'Honda', 'Black');
updateVehicle.apply(car, ['Honda', 'Black'])
console.log(car) //{ model: 'Honda', color: 'Black' }

Invoking the function with .call or .apply is a great on the fly solution. Inside of .call and .apply the first parameter is always the context to assign ‘this’. The above examples are using the car object. The key difference between the two is how the arguments are applied after the context. .apply uses the arguments in an array, while .call uses a comma to separate them.

Using Bind

Unlike .call and .apply, .bind isn’t used to invoke a function. Just like the name implies it binds the ‘this’ to the object given in it’s parameter. This way whenever the function is invoked it will automatically use the context assigned to it.

var updateCar = updateVehicle.bind(car);
updateCar('Honda', 'Black')
console.log(car) //{ model: 'Honda', color: 'Black' }

In the example above the function updateCar will always use the updateVehicle function bound to the car object. Using the same parameters as the updateVehicle function.

This is just a small dive into using the ‘this’ keyword inside of functions!

Like what you read? Give Mike Hughes a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.