Problem Statement
What does the call() method do in JavaScript?
Explanation
The call method invokes a function with a specific this value and individual arguments.
First parameter is the object to use as this inside the function. Remaining parameters are passed as individual arguments to the function.
Call executes the function immediately.
It is useful for function borrowing, where you use a method from one object on another object.
Call is commonly used to invoke parent constructors in inheritance.
Understanding call is essential for controlling this in JavaScript.
Code Solution
SolutionRead Only
// Basic call usage
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'John' };
// Call greet with person as this
greet.call(person, 'Hello', '!'); // 'Hello, John!'
// Without call, this would be undefined or window
greet('Hello', '!'); // 'Hello, undefined!' (this not set)
// Function borrowing
const person1 = {
name: 'John',
greet: function() {
console.log('Hi, I am ' + this.name);
}
};
const person2 = { name: 'Jane' };
// Borrow greet method from person1
person1.greet.call(person2); // 'Hi, I am Jane'
// Array-like objects
function sum() {
// arguments is array-like, not real array
const args = Array.prototype.slice.call(arguments);
return args.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Constructor chaining
function Animal(name) {
this.name = name;
}
function Dog(name, breed) {
Animal.call(this, name); // Call parent constructor
this.breed = breed;
}
const buddy = new Dog('Buddy', 'Labrador');
console.log(buddy.name); // 'Buddy'
console.log(buddy.breed); // 'Labrador'