What is the use Function.prototype.call method?

The call invokes a function specifying the this or the "owner" object of that function on that time of invocation.

const details = {
message: 'Hello World!',
};
function getMessage() {
return this.message;
}
getMessage.call(details); // returns 'Hello World!'

This method works like Function.prototype.apply the only difference is how we pass arguments. In call we pass directly the arguments separating them with a comma , for every argument.

const person = {
name: 'Marko Polo',
};
function greeting(greetingMessage) {
return `${greetingMessage} ${this.name}`;
}
greeting.call(person, 'Hello'); // returns "Hello Marko Polo!"

October 15, 2022
795