Tuesday 13 October 2020

call() , apply() and bind() in JavaScript

In this post, we will be discussing the difference between call(), apply(), and bind() methods of JavaScript functions with simple examples. As functions are also Objects in JavaScript, these 3 methods are used to control the invocation of the function. call() and apply() were introduced in ECMAScript 3 while bind() was added as part of ECMAScript 5.

  Bind( ) 
The bind method creates a new function and sets the this keyword to the specified object.
For example: Let’s suppose we have two person objects.
const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };

Let’s add a greeting function:
function greeting() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
  }

We can use the bind method on the greeting function to bind the this keyword to john and jane objects.
For example:
const greetingJohn = greeting.bind(john);
// Hi, I am John and I am 24 years old
greetingJohn();
const greetingJane = greeting.bind(jane);
// Hi, I am Jane and I am 22 years old
greetingJane();

Here greeting.bind(john) creates a new function with this set to john object, which we then assign to greetingJohn variable. Similarly for greetingJane.

Bind() can also accept arguments: We can also pass extra arguments to the bind method. 
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 example, the bind method creates a new function with certain parameters predefined (lang in this case) and this keyword set to the john and jane objects.

 Call ( ) 
The call method sets the this inside the function and immediately executes that function.

The difference between call() and bind() is that the call() sets the this keyword and executes the function immediately and it does not create a new copy of the function, while the bind() creates a copy of that function and sets the this keyword.

function greeting() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greeting.call(john);
  // Hi, I am Jane and I am 22 years old
  greeting.call(jane);


Above example is similar to the bind() example except that call() does not create a new function. We are directly setting the this keyword using call().

Call () can also accept arguments: Call() also accepts a comma-separated list of arguments. 

function greet(greeting) {
    console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greet.call(john'Hi');
  // Hi, I am Jane and I am 22 years old
  greet.call(jane'Hello');


 Apply ( ) 
The apply() method is similar to call(). The difference is that the apply() method accepts an array of arguments instead of comma separated values.

function greet(greetinglang) {
    console.log(lang);
    console.log(`${greeting}, I am ${this.name} and I am ${this.age} years old`);
  }
  const john = {
    name: 'John',
    age: 24,
  };
  const jane = {
    name: 'Jane',
    age: 22,
  };
  // Hi, I am John and I am 24 years old
  greet.apply(john, ['Hi''en']);
  // Hi, I am Jane and I am 22 years old
  greet.apply(jane, ['Hola''es']);

  1. bind: It binds the function with provided value and context but it does not executes the function. To execute function you need to call the function.
  2. call: It executes the function with provided context and parameter.
  3. apply: It executes the function with provided context and parameter as array.
Conclusion
We have learned that how this keyword behaves differently in JavaScript than in other object-oriented languages. The call, bind and apply methods can be used to set the this keyword independent of how a function is called.
 The bind method creates a copy of the function and sets the this keyword, while the call and apply methods sets the this keyword and calls the function immediately.
Reference: https://blog.bitsrc.io/https://www.codementor.io


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives