Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When would I use function borrowing?

Tags:

javascript

Function borrowing is borrowing the function from an object rather than redefining it; but why should I do it. We can have a generic function and objects can use them further. To be more precise; when would I use code #1 when I can code it like in code #2:

code #1

let car1 = {
  speed: 80,
  getSpeed: function () {
    return this.speed;
  },
};
let car2 = {
  speed: 60,
};
console.log(car1.getSpeed());
console.log(car1.getSpeed.call(car2));

code #2

function getSpeed() {
  return this.speed;
}
let car1 = {
  speed: 80,
}
let car2 = {
  speed: 60,
}
console.log(getSpeed.call(car1));
console.log(getSpeed.call(car2));
like image 897
atish Avatar asked Dec 18 '22 11:12

atish


1 Answers

Function borrowing is used when you already have a method defined for an object (either directly or via the prototype chain), and you want to be able to use it with a similar object that doesn't have that method defined.

This is the case in your code #1 -- rather than use prototypical inheritance or classes, the getSpeed() method was defined directly in car1. Rather than duplicate the code in car2, you can borrow from car1.

You wouldn't normally design things this way from scratch. Either you would use an ordinary function as in code #2, or you would make car1 and car2 inherit from the same prototype.

Function borrowing is usually just a workaround for poor initial design. You see it in code like

nodes = document.getElementsByClassName("foo");
result = [].prototype.map.call(nodes, someFunction);

because the NodeList prototype doesn't have its own map() function.

like image 109
Barmar Avatar answered Jan 04 '23 08:01

Barmar