Cześć, tu Jakub. Polubiłeś devFlipCards? Postaw mi kawę

3. Czym jest funkcja bind?

bind wywołany na funkcji pozwala przekazać do niej obiekt, który będzie używany jako this. Ładuje do funkcji jej kontekst.

Użyteczne, gdy funkcja traci kontekst w wyniku przypisania do zmiennej funkcji należącej do danego obiektu.

Przyjmuje jako pierwszy argument obiekt, który będzie traktowany jako this. Reszta argumentów używana jest jako argumenty, które zostaną przekazane do funkcji - jako jej argumenty.

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
Nie możesz znaleźć wspólnego terminu na spotkanie z przyjaciółmi? Sprawdź nasze narzędzie
commondate.xyz