Method borrowing, also known as function borrowing, is, as its name implies, a way for an object to use the methods of another object without redefining that same method.
In JavaScript, we can reuse the method of a function 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()
, we can borrow methods from other objects without inheriting their properties and methods.
The call()
method is used to borrow the method of one object in another object. It is called as:
object1.methodName.call(object2);
Where object1
is the object name that has the method and the object2
is the second object that is being passed to the call() method. Beacuse we want to change the context of this
to the second object.
The apply()
method does the same work except that it takes the arguments in an array form while the call()
method takes the arguments simply by comma separation.
//for call
object1.methodName.call(object2, 'argument');
//for apply
object1.methodName.call(object2, ['argument']);
The third method is bind()
also does the same thing but it solves the problem of sending the object to the call method every time. Like in the above calls the functions get executed there and then but sometimes we want to bind the context of this
and execute the function later on depending upon some event. So bind()
will bind the context of this
to the object passed to it and then we can call them anywhere we need that object’s data.
object1.displayAge.bind(object2);
The following code defines two objects, person1 and person2 :
Object person2 does not have the displayAge()
method and, as seen below, calling this method on person2
gives an error.
In the next section, the predefined JavaScript call()
, apply()
, and bind()
methods are used to invoke the displayAge()
method of the person1 object on the person2 object:
All three methods allow us to change the object referred to by this.age()
in the first code block.
There are many benefits to method borrowing:
It prevents the unnecessary duplication of code.
It allows the user to use methods of different objects without inheriting.
Using method borrowing prevents the replication of methods in multiple object blocks and saves time.