Fully Understanding the this Keyword

Today's tutorial comes courtesy of the talented Cody Lindley, from his free ebook: JavaScript Enlightenment. He discusses the confusing this keyword, and the various ways to determine and set its value.

Republished Tutorial

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in July, 2011.


Conceptual Overview of this

When a function is created, a keyword called this is created (behind the scenes), which links to the object in which the function operates. Said another way, this is available to the scope of its function, yet is a reference to the object of which that function is a property/method.

Let's take a look at this object:

Notice how inside of the getGender function, we are accessing the gender property using dot notation (e.g cody.gender) on the cody object itself. This can be rewritten using this to access the cody object because this points to the cody object.

The this used in this.gender simply refers to the cody object on which the function is
operating.

The topic of this can be confusing, but it does not have to be. Just remember that, in general, this is used inside of functions to refer to the object the function is contained within, as opposed to the function itself (exceptions include using the new keyword or call() and apply()).

Important Notes

  • The keyword this looks and acts like any other variable, except you can't modify it.
  • - As opposed to arguments and any parameters sent to the function, this is a keyword (not a property) in the call/activation object.

How is the Value of this Determined?

The value of this, passed to all functions, is based on the context in which the function is called at runtime. Pay attention here, because this is one of those quirks you just need to memorize.

The myObject object in the code below is given a property called sayFoo, which points to the sayFoo function. When the sayFoo function is called from the global scope, this refers to the window object. When it is called as a method of myObject, this refers to myObject.

Since myObject has a property named foo, that property is used.

Clearly, the value of this is based on the context in which the function is being called. Consider that both myObject.sayFoo and sayFoo point to the same function. However, depending upon where (i.e. the context) sayFoo() is called from, the value of this is different.

If it helps, here is the same code with the head object (i.e window) explicitly used.

Make sure that as you pass around functions, or have multiple references to a function, you realize that the value of this will change depending upon the context in which you call the function.

Important Note


The this Keyword Refers to the Head Object in Nested Functions

You might be wondering what happens to this when it is used inside of a function that is contained inside of another function. The bad news is in ECMA 3, this loses its way and refers to the head object (window object in browsers), instead of the object within which the function is defined.


In the code below, this inside of func2 and func3 loses its way and refers not to myObject but instead to the head object.

The good news is that this will be fixed in ECMAScript 5. For now, you should be aware of this predicament, especially when you start passing functions around as values to other functions.

Consider the code below and what happens when passing an anonymous function to foo.func1. When the anonymous function is called inside of foo.func1 (a function inside of a function) the this value inside of the anonymous function will be a reference to the head object.

Now you will never forget: the this value will always be a reference to the head object when its host function is encapsulated inside of another function or invoked within the context of another function (again, this is fixed in ECMAScript 5).


Working Around the Nested Function Issue

So that the this value does not get lost, you can simply use the scope chain to keep a reference to this in the parent function. The code below demonstrates how, using a variable called that, and leveraging its scope, we can keep better track of function context.


Controlling the Value of this

The value of this is normally determined from the context in which a function is called (except when the new keyword is used – more about that in a minute), but you can overwrite/control the value of this using apply() or call() to define what object this points to when invoking a function. Using these methods is like saying: "Hey, call X function but tell the function to use Z object as the value for this." By doing so, the default way in which JavaScript determines the value of this is overridden.

Below, we create an object and a function. We then invoke the function via call() so that the value of this inside the function uses myObject as its context. The statements inside the myFunction function will then populate myObject with properties instead of populating the head object. We have altered the object to which this (inside of myFunction) refers.

In the example above, we are using call(), but apply() could be used as well. The difference between the two is how the parameters for the function are passed. Using call(), the parameters are just comma separated values. Using apply(), the parameter values are passed inside of an array. Below, is the same idea, but using apply().

What you need to take away here is that you can override the default way in which JavaScript determines the value of this in a function's scope.


Using the this Keyword Inside a User-Defined Constructor Function

When a function is invoked with the new keyword, the value of this — as it's stated in the constructor — refers to the instance itself. Said another way: in the constructor function, we can leverage the object via this before the object is actually created. In this case, the default value of this changes in a way not unlike using call() or apply().

Below, we set up a Person constructor function that uses this to reference an object being created. When an instance of Person is created, this.name will reference the newly created object and place a property called name in the new object with a value from the parameter (name) passed to the constructor function.

Again, this refers to the "object that is to be" when the constructor function is invoked using the new keyword. Had we not used the new keyword, the value of this would be the context in which Person is invoked — in this case the head object. Let's examine this scenario.


The Keyword this Inside a Prototype Method Refers to a Constructor instance

When used in functions added to a constructor's prototype property, this refers to the instance on which the method is invoked. Say we have a custom Person() constructor function. As a parameter, it requires the person's full name. In case we need to access the full name of the person, we add a whatIsMyFullName method to the Person.prototype, so that all Person instances inherit the method. When using this, the method can refer to the instance invoking it (and thus its properties).

Here I demonstrate the creation of two Person objects (cody and lisa) and the inherited whatIsMyFullName method that contains the this keyword to access the instance.

The take away here is that the keyword this is used to refer to instances when used inside of a method contained in the prototype object. If the instance does not contain the property, the prototype lookup begins.

Notes

- If the instance or the object pointed to by this does not contain the property being referenced, the same rules that apply to any property lookup get applied and the property will be "looked up" on the prototype chain. So in our example, if the fullName property was not contained within our instance then fullName would be looked for at Person.prototype.fullName then Object.prototype.fullName.


Read the Book for Free!

JavaScript Enlightenment

This book is not about JavaScript design patterns or implementing an object-oriented paradigm with JavaScript code. It was not written to distinguish the good features of the JavaScript language from the bad. It is not meant to be a complete reference guide. It is not targeted at people new to programming or those completely new to JavaScript. Nor is this a cookbook of JavaScript recipes. Those books have been written.

Tags:

Comments

Related Articles