Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.