Understanding Call(), Bind() & Apply()

Understanding Call(), Bind() & Apply()

Table of contents

No heading

No headings in the article.

Understanding Call, Bind and Apply Methods in JavaScript

When learning JavaScript, We might have seen and word this keyword. The this keyword in JavaScript behaves differently compared to other programming languages. This causes a lot of confusion for programmers.

In other object-oriented programming languages , the this keyword always refers to current instance of the class. Where as in JavaScript , the value of this depends on how a function is called.

We can go through a example to check how this works in JS

const car = {
    name: 'Swift',
    model: 'VXI',
    color: 'Grey',
    character: function () { console.log(this.name + ' ' + this.color) }
}

now lets check how this works

car.character()

this above would be printing

 Swift Grey

Above I am calling a method named character() in the car object . hence the this keyword refers to the car object

Let's try writing a code again and check its output

const carfeatures = car.character()
carfeatures()

lets take a minute and think what could be the output

undefined undefined

Any guesses why is that happening

here we are storing the reference of car.character() to carfeatures variable. After that , we are calling it without any reference so this would be now referring to the global scope or it would be pointing to undefined in strict mode. So how can we prevent this from happening ?

we can use call(), bind() & apply() to help us go through this problem

we know that in JavaScript every thing is considered as objects even function's are also objects . so they have access to some methods and properties. Call(), Bind() & apply() as some of the methods every function inherits.

Bind() The bind method creates a new function and sets the this keyboard to the specified object

syntax:

function.bind(thisArg, optionalArguments)
function carData() {
  console.log(`Good Morning, My car name is ${this.name} and its color is ${this.color}  old`);
}

We can use the bind method on the carData function to bind this to name and color of the object

Bind does also accept arguments (comma seperated)

function.bind(this, arg1, arg2, ...)
function greeting(lang) {
  console.log(`${lang}: I am ${this.name}`);
}

const john = {
  name: 'John'
};
const jane = {
  name: 'Jane'
};

const greetingJohn = greeting.bind(john, 'en');
greetingJohn();

const greetingJane = greeting.bind(jane, 'es');
greetingJane();

In the above code block , the bind method creates a new function with certain parameters predefined

Call()

call method sets the this inside the function and immediately executes the function.

the basic difference between the call() and bind() is that call sets the this keyword and immediately calls the functions and as far as bind() is concerned it creates the copy of that function and then sets this keyword.

function greeting(lang) {
  console.log(`${lang}: I am ${this.name}`);
}

const john = {
  name: 'John'
};
const jane = {
  name: 'Jane'
};

greeting.call(john);
greeting.call(jane);

this example above is same as bind() except it does not creates new function . we are directly setting up this in the call

call can also accept arguments just like bind does comma separated.

Apply()

Apply method is also similar to call but the only difference is that it accepts array of arguments instead of comma separated values

function greeting(lang) {
  console.log(`${lang}: I am ${this.name}`);
}

const john = {
  name: 'John'
};
const jane = {
  name: 'Jane'
};

greeting.apply(john, ['hi', 'en']);
greeting.apply(jane, ['hi', 'en']);

Now we all have understood that how the this keyword works.