bind
called on function allows to pass an object to this function, which will be used as this
inside it. It loads context into function.
Useful, when function loses it's context as a result of assigning function beloning to that object to some variable.
First argument is an object, which will be passed as this
to the function. Rest of args will be used as arguments, which will be passed to the function as regular arguments.
const person = { firstName: "Mario", print: function (arg1) { console.log(`I'm ${this?.firstName} and this is an arg: ${arg1}`); }, }; person.print(); // I'm Mario and this is an arg: undefined const printFunction = person.print; printFunction(); // I'm undefined and this is an arg: undefined const boundPrintFunction = person.print.bind(person); boundPrintFunction(); // I'm Mario and this is an arg: undefined const boundedArgPrintFunction = person.print.bind(person, "myArg"); boundedArgPrintFunction(); // I'm Mario and this is an arg: myArg