In this article, we are going to learn about the Javascript call, apply and bind methods in detail with the examples.

In javascript, all functions are objects and these three methods of javascript are used to control the invocation of the function.

Before going further with the article, you first have to familiar with the ‘this‘ keyword uses in javascript. Everything in javascript is an object and every object has a ‘this‘ keyword assigned to it,

Here, I am only explaining a little bit about the use of ‘this‘ keyword. If you want to learn in more details then you can check this article.

Javascript ‘this’ Keyword

Javascript ‘this‘ keyword allows you to reuse functions with different contexts.

In JavaScript, the value of ‘this‘ depends on how a function is called.

Let’s understand this with a simple example

const user = {
  firstName: 'John',
  lastName: 'Doe',
  fullName: function() {
    console.log(this.firstName + ' ' + this.lastName);
  }
};

Here, we have a user object which contains three properties firstName, lastName and fullName.

Now let’s execute the below code

console.log(user.fullName());

This will print ‘John Doe

Here, I am calling the fullName() method using the user object, so ‘this’ keyword inside the method refers to the user object. Let’s write the below snippet at the end of the above code.

const printFullName = user.fullName;
printFullName();

above code will print ‘undefined undefined‘, strange is it?

Now, from here, you have to give more attention to understand why this happen and why ‘this‘ keyword is so confusing for the javascript beginners.

In the above code, we are storing the reference of user.fullName to variable printFullName. So ‘this’ will now refer to the window (global) object or undefined (in strict mode).

So is there any way to overcome with this issue?

Yes, by using the javascript call, apply and bind methods, we can overcome the reference issuer of javascript ‘this‘ keyword.

Basic Rules to Remember for Javascript ‘this’ keyword

  • this‘ refers to an object which calls the function it contains.
  • this‘ always refers to an object.
  • In the global context, ‘this‘ refers to either window object or is undefined if the ‘strict mode’ is used.

Javascript call() method

Javascript call() method is used to call a function with a given this and arguments provided to it individually.

That means, we can any function specifying the reference.

It is really very difficult to understand the javascript call() method by just reading the few lines. So let’s understand it with a simple example

const post = {
  title: 'My First Post On Call',
  author: 'sachin',
}

function summary() {
  console.log(`${this.author} wrote an article which title was ${this.author}.`)
}

summary();  // undefined undefined

Here, we created a simple post object with two properties title and author and a function summary.

When we call simple summary() then it will print ‘undefined wrote an article which title was undefined.’

Because post and summary don’t have any reference yet. And on calling the summary function, it’s looking for those properties on the global object.

Now you can see the magic of the javascript call() method which create a reference between the post and summary.

summary.call(post);  //sachin wrote an article which title was My First Post On Call.'

Now we can see the desire output in the console because there is a connection now between post and summary.

When we use summary.call(post) then ‘this’ actually becomes the object passed as an argument.

You can also pass an argument on the call method of the javascript.

const person = { 
    name: 'Sachin'
}

function greeting(country) {
    console.log(`${person.name}, you are welcome to ${country}`);
}

greeting.call(person,'India'); //Sachin, you are welcome to India

Javascript apply() method

Javascript apply() method is same as call() method. Let’s understand it with below example

const person = { 
    name: 'Sachin'
}

function greeting(country) {
    console.log(`${person.name}, you are welcome to ${country}`);
}

greeting.apply(person,['India']); //Sachin, you are welcome to India

See, similarly to the call() method, first argument in the apply() method sets the ‘this‘ value which is the object.

The only difference of apply() with the call() method is that the second argument of the apply() method accepts the arguments to the actual function as an array.

Javascript bind() method

Javascript bind() method creates new function. It allows you to set the values now and use it in future.

Let’s understand this method also with a simple example given below

function greeting(lang) {
  console.log(`${lang}: I am ${this.name}`);
}
const sachin = {
  name: 'Sachin'
};
const john = {
  name: 'John'
};
const greetingSachin = greeting.bind(sachin, 'en');
greetingSachin();
const greetingJohn = greeting.bind(john, 'uk');
greetingJohn();

You can see in the above code, bind method creates a new function and this keyword set to the obj sachin and john and the rest of the parameters following the first parameter in the bind() method are passed as arguments.

Difference between Javascript call, apply and bind methods

Javascript bind() method creates a copy of the function and sets ‘this‘ keyword, while the call() and apply() methods sets ‘this‘ keyword and calls the function immediately.

When to use JavaScript call, apply and bind methods

All these methods behave the same and so it is really very difficult to understand the use of these methods in the real-time coding.

You can use bind() method when you want that function to later be called with a certain context, useful in events.

The call() or apply() methods can be used when you want to invoke the function immediately, and modify the context.

Conclusion

That’s all for these three javascript methods. You just learn the basic of javascript call, apply and bind method in this article.

For javascript beginners, it is really very confusing and tough topics to understand but in this article, I tried my best to explain it in very easy way with simple examples.

To clarify the concept of javascript call(), apply() and bind method, you have to do the practice and use it with real-time examples.

If you have any doubts or queries then you can comment in the comment box or you can join our Facebook group where you can share your experience or ask any web development related queries.

Codecademy Web Development
Pin It