Practical application of .apply(), .call(), and .bind()

call (and apply) allow you to execute a method within a specific this context. It’s a different way to call a function. "foo".repeat(5) is functionally the same as String.prototype.repeat.call("foo", 10). It is a necessary part of the language (sometimes you have no option but to call something that way, or you have to borrow a method from another context). You may not encounter it that much, it’s very useful though.

apply allows you to pass arguments as an array to a function that expects individual arguments. Eg Math.max takes individual arguments, but say you wanted to find the max of an array, so just use apply to pass an array: Math.max.apply(null, myArray). Note the spread operator has obsoleted that use case (just do Math.max(...myArray)).

bind allows you to create a function that wraps another function in a specific context, so you can execute it later. You’ll see it a lot in JS classes, for example with React, where you have handler functions to deal with clicks etc. Often those are bound in the constructor like this.myHandlerMethod = this.myHandlerMethod.bind(this) , which looks a bit silly, but JS scope is tricky at times, and what that is doing is ensuring that the handler will always be called in the context of the class in which it was defined. Arrow functions make bind a lot less necessary than it used to be.

Call, apply and bind allow you to change the context of a function when it is called.

Call and apply are a different way of executing a function, bind is a way of changing the way a function will be executed.

4 Likes