Trusted answers to developer questions

What is Method Borrowing?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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 :

Console
Code Defining Person 1 and person 2

Object person2 does not have the displayAge() method and, as seen below, calling this method on person2 gives an error.

Console
Calling the displayAge() function on person2

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:

Console
Using the call(), bind() and apply() methods

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:

  1. It prevents the unnecessary duplication of code.

  2. It allows the user to use methods of different objects without inheriting.

  3. Using method borrowing prevents the replication of methods in multiple object blocks and saves time.

RELATED TAGS

method borrowing
javascript

CONTRIBUTOR

Elite_Alphas
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?