As we have learned in part 1 of our series, functions are first class objects, which gives them full access to properties and methods. In part 2, we examined call and apply. In the following post we will cover another core method of the Function object, bind. Let’s dive in.
Definition
bind – method of the Function object that creates a new function that when called has it’s this value mapped to the given parameter and uses the set arguments.
bind returns a new function with the value of this locked (bound) to a function.
Syntax
bound function
bound function with a parameter
Why/when would you use this function?
you want to lock in the value of this, helpful for event handlers (see: example 1 and example 3)
you want to “partially apply” functions by locking in arguments (see: example 2)
Examples
Example 1 - locking in the value of this
So what happened in our previous example? Why was “Component” printed and not “Global”? The reason is that we bound the this value to our component object. Even though the first call to getName() returns “Global”, we subsequently locked the value of this to the component in our bound function.
Example 2 - partial function application
We can also utilize bind to create a function with a predefined set of arguments.
We have set the “x” value and pass in the value of “y” whenever we call our “triple” function. Notice in this example how we passed in null for the value of this and also passed in the values last (this follows our function signature).
Example 3 - using bind in event handling
This is a more complex example to highlight the usage of bind. Please be sure to read the comments as this example is showcasing a few different concepts.
The Function object is a fundamental component of the JavaScript language and learning to leverage its bind method can help us simplify code and promote reusability. Through examples, we have observed how bind can be used to lock in the value of this, which is helpful to borrow functions and to ensure we are targeting the correct object in our programs (e.g. in event handlers). By leveraging bind we can also create partially applied functions that allow us to reuse arguments and functionality. For further reading, check out the additional resources below and be sure to try out your own examples.