call() / apply() / bind() in JavaScript

Introduction

call() / apply() / bind() in JavaScript

* call() and apply() that immediately runs a function.

* bind() return a new function with a certain context and parameters.

1. call()

In JavaScript, when a.call() is called, invoke the function. All functions when created have this property called call() that allows us to call the function.

a() this is a shorthand of a.call().

function a(){
  console.log("hello")
}
a.call()
a() 
hello
hello

Example)

call() method can borrow methods of other objects.

const wizard = {
  name: "Merlin",
  health: 50,
  heal() {
    return (this.health = this.health + 10);
  },
};

const archer = {
  name: "Robin Hood",
  health: 30,
};

wizard.heal.call(archer)
console.log(archer)
{ name: 'Robin Hood', health: 40 }
  • call() has other parameters that it can receive it can receive arguments so that we can give archer or heal method parameters.

2. apply()

const wizard = {
  name: "Merlin",
  health: 50,
  heal(num1, num2) {
    return (this.health += num1 + num2);
  },
};

const archer = {
  name: "Robin Hood",
  health: 5,
};

console.log("first", archer);
wizard.heal.call(archer, 50, 30);
console.log("second", archer);
first { name: 'Robin Hood', health: 5 }
second { name: 'Robin Hood', health: 85 }

apply()

The only difference between call() and apply() is that instead of call() that just takes parameters 50, 30. However, apply that takes an array of parameters [50,30].

const wizard = {
  name: "Merlin",
  health: 50,
  heal(num1, num2) {
    return (this.health += num1 + num2);
  },
};

const archer = {
  name: "Robin Hood",
  health: 5,
};

console.log("first", archer);
wizard.heal.apply(archer, [50, 30]);
console.log("second", archer);
first { name: 'Robin Hood', health: 5 }
second { name: 'Robin Hood', health: 85 }

3. bind()

const wizard = {
  name: "Merlin",
  health: 50,
  heal(num1, num2) {
    return (this.health += num1 + num2);
  },
};

const archer = {
  name: "Robin Hood",
  health: 5,
};

const healarcher = wizard.heal.bind(archer, 50, 30);
console.log(healarcher())
85
  • bind() return a function. So, It should be called like healarcher().

call() and apply() are useful for borrowing methods from an object while bind() is useful for us to call functions later on with a certain context or certain this keyword.

bind() with function currying

function multiply(a, b) {
  return a * b;
}
let multiplyByTwo = multiply.bind(this, 2);
console.log(multiplyByTwo(3));
6

Leave a Reply

Your email address will not be published.

ANOTE.DEV