The Final Steps to Mastering JavaScript’s “this” Keyword

An excerpt from http://www.sitepoint.com/mastering-javascripts-this-keyword/, by @

In a previous article we learned the fundamentals of using JavaScript’s this keyword properly. We saw that the crucial factor in determining what this refers to, is to find out the current execution context. However, this task can be a bit tricky in situations where the context gets changed in a way we don’t expect. In this article I will highlight when this might happen and what we can do to remedy it.

Fixing Common Issues

In this section we’ll explore some of the most common issues arising from the use of the this keyword and we’ll learn how to fix them.

  1. Using this in Extracted Methods

One of the most common mistakes that people make is when trying to assign an object’s method to a variable and expecting that this will still point to the original object. As we can see from the following example, that simply doesn’t work.

var car = {
  brand: "Nissan",
  getBrand: function(){
    console.log(this.brand);
  }
} ;
 
var getCarBrand = car.getBrand;
     
    getCarBrand();   // output: undefined
    JS Bin

Even though getCarBrand appears to be a reference to car.getBrand(), in fact, it’s just another reference to getBrand() itself. We already know that the call-site is what matters in determining the context, and here, the call-site is getCarBrand(), which is a plain and simple function call.

To prove that getCarBrand points to a baseless function (one which isn’t bound to any specific object), just add alert(getCarBrand); to the bottom of the code and you’ll see the following output:

function(){
  console.log(this.brand);
}

getCarBrand holds just a plain function, which is no longer a method of the car object. So, in this case, this.brand actually translates to window.brand, which is, of course, undefined.

If we extract a method from an object, it becomes a plain function again. Its connection to the object is severed, and it no longer works as intended. In other words, an extracted function is not bound to the object it was taken from.

So how can we remedy this? Well, if we want to keep the reference to the original object, we need to explicitly bind the getBrand() function to the car object when we assign it to the getCarBrand variable. We can do this by using the bind() method.

   var getCarBrand = car.getBrand.bind(car);
    getCarBrand();   // output: Nissan

Now, we get the proper output, because we successfully redefine the context to what we want it to be.

Continue reading this article on SitePoint!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.