apply
invoked on a function allows to pass an object, which will be used as this
. It loads context of the function
apply
is different from bind
- in apply
function is invoked immediately with parameters passed as a second argument of apply
. This second argument is an array of parametres, which will be passed to function in the same order.
const person = { firstName: "Mario", print: function (arg1, arg2) { console.log( `I'm ${this?.firstName} and this is an arg1: ${arg1} and arg2: ${arg2}` ); }, }; person.print(); // I'm Mario and this is an arg1: undefined and arg2: undefined const printFunction = person.print; printFunction(); // I'm undefined and this is an arg1: undefined and arg2: undefined printFunction.apply(person); // I'm Mario and this is an arg1: undefined and arg2: undefined printFunction.apply(person, ["arg1", "arg2"]); // I'm Mario and this is an arg1: arg1 and arg2: arg2
apply
is different from call
- in apply
arguments passed to function are taken from array passed as second argument, while in call
they are speparated with comma.
printFunction.apply(person, ["arg1", "arg2"]); // I'm Mario and this is an arg1: arg1 and arg2: arg2 printFunction.call(person, "arg1", "arg2"); // I'm Mario and this is an arg1: arg1 and arg2: arg2