use cases for bind, call and apply

Michael Scoggins

Michael Scoggins |


10/25/2020

use cases for bind, call and apply

this gets pretty in-depth depending on your level of understanding of the concept of this in JavaScript.

assuming that you fully understand that:

.bind() will bind this to an object of your choice, even when it is called outside of that context (where it was first defined in some method on a different object). it is used for a later callback (as you create a new variable to bind).

.call() does the same thing except you don’t have to create a new variable, as it is used immediately. additionally, its first argument indicates which object’s context this refers to, and the remaining arguments represent the arguments to whatever function you’re calling, if it has any.

.apply() does the same thing as .call(), except it accepts an array of arguments as a second argument (after the first argument which indicates the context for this, if necessary).

for example:

the first argument is null because “this” does not apply (no pun intended
 really) in this particular example

notice how the function is applied to each item from a given array. by contrast, check out .call():

the arguments are passed directly to .call()’s parameters, simply separated by commas.

important to note, however, is that ever since ES6, with arrow functions, these methods are not exactly necessary. one can simply call on a method which references this, and return it as an anonymous callback:

onClick={() => someMethod()}

which works because arrow functions do not bind to the this keyword, so this will always reference its caller (which greatly simplifies such callback patterns).

but you will certainly continue to see classic patterns as well.