Borrow a Method Using Bind

Borrow a Method Using Bind

let's consider, we have two calculate the age of two different people

const obj1={
firstName:"john"
lastName:"Doe"
yearOfBirth:1999
calcAge=function(){
console.log(`${this.firstName}${this.lastName} age is `${2022-this.yearOfBirth}`)
}

}

in the obove object we declared some properties and one method which will give us the age of the person

lets declare other person detials and will try to calculate the age of second person

const obj1={
firstName:"mark"
lastName:"Doe"
yearOfBirth:1997
calcAge=function(){
console.log(`${this.firstName}${this.lastName} age is `${2022-this.yearOfBirth}`)
}

}

Both will works fine and will gives us the result like

obj1.calcAge() // johnDoe age is 23

obj2.calcAge() // johnDoe age is 25

for this we should know how Keyword THIS behaves in javacript but here we will discuss about THIS in short

THIS keyword

In simple terms THIS is a variable it holds different value at different scenarios

ex :1.In Method(regular function inside object) ====> this holds the Object which called that method

2.regular function ==>window Object

3.arrow function(arrow function dont have the THIS keyword so it will picks up the its parent THIS Keyword)

so in our exmaples we are using method and inside that we are using THIS keyword so there, THIS points to the Object which called that method So that object has the firstName and other properties so we will get the output.

But If we observe both objects and their method , both methods is like same and doing same Work so we have to do something so then without writing same method twice we have to achieve the Result.

In JavaScript, we can reuse the method on a different object other than the object it was defined on. Method borrowing helps to keep us from having to write the same code multiple times. Using the predefined JavaScript methods, call(), apply() or bind()

``const obj1 = { firstName:"john" lastName:"Doe" yearOfBirth:1999 calcAge=function(){ console.log(${this.firstName}${this.lastName} age is ${2022-this.yearOfBirth}) } }; person1.calcAge();

const obj2 = { firstName:"john" lastName:"Doe" yearOfBirth:1997 };

/Using the call() method/ obj1.calcAge.call(person2); //Output: He is 25 years old

/Using the bind() method/ obj1.calcAge.bind(person2); //Output: He is 25 years old

/Using the apply() method/ obj1.calcAge.apply(person2); //Output: He is 25 years old ```

so we are calling the method inside obj1 and we are telling to the JS now this time THIS needs to points to the passed argument from call or bind or apply so methods will picks the properties of passed argument.

advantages of using Method borrowing: 1.DRY (we don't repeat the same method agian and agian) 2.Less code and Saves our time 3.It allows the dev to use methods of different objects without inheriting.