JavaScript Call, Apply, and Bind Methods

Introduction

1. Call, Apply and Bind methods are used to store the object reference in 'this' keyword of function.

2. When function's 'this' have reference of object, then we can access states and behaviours of that object.

3. For practice we will use these objects as reference.

let human1 = {
  name: "Chombi",
  age: 20,
};

let human2 = {
  name: "Dinga",
  age: 19,
};

let human3 = {
  name: "Nimbi",
  age: 18,
};

Below function we will use to access object's properties by using call, apply and bind methods.

function detailsAll(a, b, c) {
  console.log("Name : " + this.name);
  console.log("Age : " + this.age);
  console.log("value of a : " + a);
  console.log("value of b : " + b);
  console.log("value of c : " + c);
}

Call Method

1. Call method accepts object reference as first argument and accepts 'n' number of arguments.

2. Here, arguments are passed to the function's parameter list.

3. It will call the function immediately.

4. Example: Print name, age of object human1 and print function arguments.

detailsAll.call(human1, 10, 20, 30);

Output:

Name : Chombi 
Age : 20 
value of a : 10 
value of b : 20
value of c : 30

Apply Method

1. Apply method accepts 2 arguments where object reference is first argument and 2nd argument is the array of arguments.

2. Here arguments are passed to the function's parameters list.

3. It will call the function immediately.

Example: Print name, age of object human2 and print function arguments.

detailsAll.apply(human2, [11, 22, 33]);

Output:

Name : Dinga 
Age : 19 
value of a : 11 
value of b : 22
value of c : 33

Bind Method

1. Bind method accepts object reference as 1st argument and accepts 'n' number of arguments.

2. Here 'n' number of arguments are passed to the function's parameter list.

3. It will not call the function immediately.

4. It returns a new function in which 'this' keyword is pointing to the object reference we have passed.

5. To execute the function we need function reference and parenthesis.

Example: Print name, age of object human3 and print function arguments.

let func = detailsAll.bind(human3, 77, 88, 99);
func();

Output:

Name : Nimbi 
Age : 18 
value of a : 77
value of b : 88
value of c : 99