Hard-Bind a Function's this Value with the .bind() Method

Marius Schulz
InstructorMarius Schulz
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

The Function.prototype.bind() method lets us permanently tie a function's this argument to a specific value. It creates a new bound function that calls the original function with the provided this argument, no matter how that bound function is called.

In this lesson we'll see how to use the bind() method. To better understand how it works, we'll implement a naive version of bind() ourselves.

Instructor: [00:00] When we try to pass a method as a call back to another function, we often times lose the intended receiver of the method. The time out cause the call back with the this argument set to the global object, which is not what we intended.

[00:14] We can solve this problem by using the bind method. Bind will create a new sayHi function and permanently set as this value to person. This mechanism is sometimes referred to as hard binding. We can then pass the hard bound function to set time out.

[00:36] Now, sayHi is called with the correct this argument. Even if we extract our bound function into a variable, and invoke that variable as a function, the this argument is still tied to person. Once the function is bound, it's this argument can no longer be changed, not even by call or apply.

[01:09] We still see John's name in the output, not James, because the greet function is bound to person. Let's go ahead and build our own version of the bind method to better understand how it works. Bind is defined on the function prototype and it accepts a this arg that we want to bind to.

[01:32] What does bind return? Well, it returns another function. We will store a reference to the original function in the func variable, and later use apply to invoke it within our inner function. We also need to take care of any arguments that the caller of our inner function might provide. We'll just pass them along to our original function.

[01:59] Finally, bind allows us to fix a number of arguments ahead of time when we bind the original function. When our new function is invoked, the two argument lists are combined. We are effectively doing partial application here.

[02:14] First, we provide all fixed arguments and we can catenate all dynamic ones. This is still not a spec complaint implementation, so please don't use it anywhere. The native bind method is available in pretty much every browser, since IE9, so you might not even need a polifo.

Kevin Pinny
Kevin Pinny
~ 6 years ago

Important to note that a hard binding can be overwritten by invoking the function with new keyword. So in other words the order of precedence of this is: implicit, explicit (call, apply), hard binding and the one that overrules them all is new.

Markdown supported.
Become a member to join the discussionEnroll Today