What is the use Function.prototype.apply method?
The apply
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.apply(details); // returns 'Hello World!'
This method works like Function.prototype.call
the only difference is how we pass arguments. In apply
we pass arguments as an array.
const person = {
name: "Marko Polo"
};
function greeting(greetingMessage) {
return `${greetingMessage} ${this.name}`;
}
greeting.apply(person, ['Hello']); // returns "Hello Marko Polo!"