Revealing the Inner Workings of JavaScript's "this" Keyword

Originally published at: http://www.sitepoint.com/inner-workings-javascripts-this-keyword/

To know a programming language doesn’t mean that you understand it or are using it properly. It’s the same with JavaScript. Although it’s an easy language to learn, there are many pitfalls for novices, and even for seasoned programmers.

One thing that confuses inexperienced developers is how the this keyword works. Put simply, this is a referencing alias—it’s just knowing what exactly it references, that is the tricky part.

This article aims to dispel the confusion and offer an insight into the inner workings of the this keyword.

So, What is this Anyway?

In a nutshell, this is a special identifier keyword—automatically defined in the scope of every function—pointing to the “owner” of the function being executed. But, to fully grasp its tricky nature, we need to answer two key questions:

How is this Created?

Each time a JavaScript function is invoked, a new object is created containing information about which parameters were passed, how the function was invoked, where the function was called from, and so on. One of the main properties of that object is the this reference, which is automatically bound to the object of which the function is a method.

Note: for the curious, this is detailed in §10.4.3 of the ECMAScript Language Specification and the sections which that links to.

var car = {
  brand: "Nissan",
  getBrand: function(){
    console.log(this.brand);
  }
};

car.getBrand();
// output: Nissan

Try it out in JS Bin

In this example this, used in this.brand, is a reference to the car object. So, this.brand is the same as car.brand.

What Does this Refer to?

The value of this, passed to all functions, is based on the context in which the function is called at run-time. The scope of this isn’t concerned with how and where functions are declared, but rather where they are called from (i.e. the context).

Every line of JavaScript code is run in an execution context. The object that this refers to is redefined every time a new execution context is entered and remains fixed until it’s shifted to a different context. To find the execution context (and this binding) we need to find the call-site—the location in the code where a function is called from (not where it’s declared).

Let’s demonstrate this in the following example:

var brand = 'Nissan';
var myCar = {brand: 'Honda'};

var getBrand = function() {
  console.log(this.brand);
};

myCar.getBrand = getBrand;
myCar.getBrand();
// output: Honda

getBrand();
// output: Nissan

Try it out in JS Bin

Even though both myCar.getBrand() and getBrand() point to one and the same function, the value of this is different because it’s based on the context in which getBrand() is being called.

As we already know, within a function, this is bound to the object of which the function is a method. In the first function call, the object is myCar, while in the second, the object is window (getBrand() is the same as window.getBrand()). So, a different context yields different a result.

Continue reading this article on SitePoint
1 Like

You might want to consider adding to your article regarding the new ES6 functions that treat this differently (to reduce the need to use bind when attaching functions to event listeners.

Hi @felgall
ES6 arrow functions will be explored in my upcoming tutorial about the tricky parts of using the this keyword.

1 Like

Wonderful article Ivaylo. You did a great job examining those elusive and sometimes down right pesky nuances of the ‘this’ keyword. Each of the contexts were explained clearly and concisely. Very helpful. Thank you!

Thank you WebDevArtist. I’m glad that you see the article in that way, because this was my goal when I wrote it.

I think it is always worth to mention the first tricky trap: this in callback functions of the promise:

doSomethingAsync().then(
    function () {
        this.WhyIDONotWorkHere();
    },
    function () {}
)

For which framework do you mean there? For when using jQuery, the first function occurs when done, the second when fail, and there’s a third one for progress.

I am glad somebody has taken the time to explain what “this” means in the javascript world. Such a simple word and meaning in the english language it get’s so confusing in code. You did an awesome job with the code block examples. I also have found Derick Bailey’s free course about “this” helpful as well. http://derickbailey.com/email-courses/masteringthis/ Thank you Ivaylofor! Thank you for sharing your time to teach about the “this” keyword.

Thank you @ianposton

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