JavaScript – 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.

Leave a Reply

Your email address will not be published.

ANOTE.DEV