call, apply and bind methods JavaScript

Let's consider an object having a few properties and a method as below

const person1 = {
  first: "will",
  last: "smith",
  role: "actor",
  getInfo: function () {
    console.log(this.first + " " + this.last + "is" + this.role);
  },
};

console.log(person1);

It consoles to
Alt Text
JavaScript attaches some behind the scenes things to objects.
Here with the getInfo, JS has attached certain methods including call, apply and bind.

Let's dig deep into them

Consider another object

const person2 = {
  first: "taylor",
  last: "swift",
  role: "singer",
};

What if we want to use getInfo method on person2, rather than copying it, we can borrow it from person1 object (function borrowing)

const person2 = {
  first: "taylor",
  last: "swift",
  role: "singer",
};

// function borrowing
person1.getInfo.call(person2)

// console
// taylor swift is singer

In the function borrowing, this points to the object passed within parathesis.

But generally, if method is to be used in multiple objects, we keep this outside the objects

const person1 = {
  first: "will",
  last: "smith",
  role: "actor",
};

const getInfo = function () {
    console.log(this.first + " " + this.last + "is" + this.role);
}

getInfo.call(person1)

const person2 = {
  first: "taylor",
  last: "swift",
  role: "singer",
};

getInfo.call(person2)

// console
// will smith is actor
// taylor swift is singer

side example,what if getInfo has its own arguments. Then this keyword points to first argument

const person1 = {
  first: "will",
  last: "smith",
  role: "actor",
};

const getInfo = function (place) {
    console.log(this.first + " " + this.last + "is" + this.role + " from " + place);
}

getInfo.call(person1, "mars")

const person2 = {
  first: "taylor",
  last: "swift",
  role: "singer",
};

getInfo.call(person2, "earth")

// console
// will smith is actor from mars
// taylor swift is singer from earth

Moving towards apply method
Only difference between call & apply method is the way, we pass additional parameters to the method, for the above example, apply will work like this

getInfo.apply(person1, ["mars"])
getInfo.apply(person2, ["earth"])

Now bind method

bind & call methods are also similar, bind method instead of invoking/calling it, it returns the copy of the method, which can be invoked later, let's see the example

let info1 = getInfo.bind(person1, "mars")
info()

//or

getInfo.bind(person1, "mars")()

// console
// will smith is actor from mars

We call the above behaviour as function currying, more about this in the coming blog -- stay tuned

28