Problem Statement
What is function borrowing in JavaScript?
Explanation
Function borrowing is using a method from one object on another object using call, apply, or bind.
The borrowed method operates on the borrower object as if it were its own method.
Common use case is borrowing array methods for array-like objects.
Function borrowing enables code reuse without inheritance.
It is a powerful technique in JavaScript for leveraging existing methods.
Understanding function borrowing shows mastery of this and context.
Code Solution
SolutionRead Only
// Basic function borrowing
const person1 = {
name: 'John',
greet: function() {
console.log('Hello, I am ' + this.name);
}
};
const person2 = { name: 'Jane' };
// Borrow greet from person1
person1.greet.call(person2); // 'Hello, I am Jane'
// Array method borrowing (very common)
function sum() {
// arguments is array-like, not array
const arr = Array.prototype.slice.call(arguments);
return arr.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
// Modern alternative
function sum2(...args) {
return args.reduce((total, num) => total + num, 0);
}
// Borrowing array methods for NodeList
const divs = document.querySelectorAll('div');
// divs is NodeList, not Array
// Borrow forEach
Array.prototype.forEach.call(divs, function(div) {
console.log(div);
});
// Borrow map
const texts = Array.prototype.map.call(divs, function(div) {
return div.textContent;
});
// Object method borrowing
const obj1 = {
data: [1, 2, 3],
printData: function() {
console.log(this.data);
}
};
const obj2 = { data: [4, 5, 6] };
obj1.printData.call(obj2); // [4, 5, 6]
// Practical example - checking array
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
console.log(isArray([1, 2, 3])); // true
console.log(isArray('hello')); // false
// hasOwnProperty borrowing (safe)
const obj = Object.create(null);
// obj.hasOwnProperty('x'); // Error! (no prototype)
const result = Object.prototype.hasOwnProperty.call(obj, 'x');
console.log(result); // false (safe!)
// Borrowing Math methods
const numbers = { 0: 5, 1: 2, 2: 9, length: 3 };
const max = Math.max.apply(null,
Array.prototype.slice.call(numbers, 0, numbers.length)
);
console.log(max); // 9