I've started to learn about functions and this keyword. While learning about the call() and its usecase I found myself unclear of the below two scenarios which yields the same output
Method Borrowing:
const lufthansa = {
airline: 'LUFT',
iataCode: 500,
bookings: [],
book(name) {
console.log(`${name} booked Airline: ${this.iataCode}-${this.airline}`)
this.bookings.push({booking: `${name} booked Airline: ${this.iataCode}-${this.airline}`})
}
}
const euroWings = {
airline: 'EW',
iataCode: 700,
bookings: []
}
euroWings.book = lufthansa.book
lufthansa.book('John')
euroWings.book('Adam')
Using Call()
const lufthansa = {
airline: 'LUFT',
iataCode: 500,
bookings: [],
book(name) {
console.log(`${name} booked Airline: ${this.iataCode}-${this.airline}`)
this.bookings.push({booking: `${name} booked Airline: ${this.iataCode}-${this.airline}`})
}
}
const euroWings = {
airline: 'EW',
iataCode: 700,
bookings: []
}
lufthansa.book('John')
lufthansa.book.call(euroWings, 'Adam')
What are the real differences and when one should be used?
.call()
is generally used when you don't control the methods of the object, and want to use methods from some other object.
The classical example is using array methods on "array-like" objects that exist in the web interface, such as NodeList
.
divs = document.getElementByClassName("myclass");
result = [].map.call(divs, function(div) { return div.getAttribute("someattr"); });
You could conceivably do
div.map = [].map;
result = div.map(function(div) { return div.getAttribute("someattr"); });
but borrowing the method every time would be repetitive.