Simple use of .bind() in JavaScript

Posted on Nov 24, 2014


In the last post, we discussed using this in JavaScript and how it might not refer to what you want or expect it to.

In this post we will look at using .bind() to force JavaScript do your bidding when it comes to using the this that you want it to.

Create a Method

In simple terms, .bind() sets the context for this based on what you pass in as a parameter. Remember that this essentially functions as an argument in the function in which it appears, and it is always created in every function. That means we can always assign it any value we wish, just as we could do with an explicitly created argument. First lets start with an object with a method.

Hijack the Method

Let’s say that Sir Allan Sammy Boy is desperate for some attention, so he comes along and interrupts your conversation just as Carlton is introducing himself. He hijacks Carlton’s this by injecting himself into the function with .bind(). He does this by creating a new function and passing the result of .bind() to the new function.

In the above example, when the new function is executed, using .bind() explicitly tells the hijacked .salutation() method what to use for this when the function is executed. It does not overwrite the original object, so Carlton can still drop in after the rude interruption to introduce himself:

Submit a Comment

Your email address will not be published. Required fields are marked *