The this keyword in JavaScript (simple explanation)
Last updated: March 11, 2022.
Understanding the this keyword in JavaScript can be challenging at first because it does not refer to a fixed object.
Instead, like the use of the word this in everyday life, what it refers to depends on context.
What ‘this’ means depends upon the context
The meaning of the word this varies in everyday usage.
If someone were to stand in front of the Eiffel Tower and point to it saying ‘this’, it would be clear to you from the context that ‘this’ refers to the Eiffel Tower.
Likewise, if someone were to stand in front of the leaning tower of Pizza and point at it saying ‘this’, it would be clear that ‘this’ now refers to the leaning tower of Pizza.
In everyday usage, the meaning of this varies dependent upon context.
This is exactly the same in JavaScript: what the keyword this refers to depends upon the context.
What does the keyword this refer to in JavaScript?
What the keyword this refers to changes depending upon the context.
But it is not random! It points predictably in one direction: towards it parent data object.
So, if this is used inside a JavaScript object, it refers to the object in which it is nested:
const myObject = {myMethod: function() { console.log(this); } } myObject.myMethod() // Logs myObject to the console
This is the main use case for the word this in JavaScript.
Now we have established that this points to its parent data object, let’s see this in action with some examples.
Usage examples of the this keyword
In global environment
You may be wondering what the keyword this refers to when used in the top-level, global environment (i.e. when it is not nested in a data object).
In this special case, the keyword this refers to the global window object:
console.log(this); // Output: window object
But this is more of a point of curiosity because it doesn’t add any value in the content over simply calling window:
console.log(window); // Output: window object
Thus, though you may see the keyword this used in the global environment, it doesn’t add much value there.
In functions and block statements
The keyword this is not contained by functions or block statements, such as loop or if/else conditional statements.
This is because they are not data objects in the sense that data can be stored in them.
In functions and block statements, the keyword this simply ignores them and refers to the parent data object.
So if functions and block statements are written in the global environment, this refers to the global window object:
/* Calling 'this' within a function */ function myFunction() { console.log(this); // returns window object } myFunction() /* Calling 'this' within a loop */ for (i=0; i<1; i++) { console.log(this); // returns window object }
In a JavaScript object
When used within a JavaScript object, the keyword this refers to the object in which it is contained.
This makes it possible to store functions in objects that call upon data within the object using the keyword this:
const user = { firstName: "JavaScript", lastName: "Developer", printName: function() { console.log(this.firstName + " " + this.lastName); } } user.printName() // "JavaScript Developer"
Avoid using ES6 arrow functions inside data objects with the keyword this!
This is a major gotcha in JavaScript: used in an arrow function within an object, this will refer to the global window object rather than its parent data object.
It is best to use a standard anonymous function like the one above to avoid this counter-intuitive behavior. If you wish to access the global window object, call window
instead.
Now, this example would still work just as well if the keyword this were replaced by myObject
. So why use this?
The advantage of using the keyword this keyword in this context is that the data (firstName
, lastName
) and functionality (printName
) is not dependent upon the name of the object.
This means that the data and function could be used in another object in exactly the same way. In other words, the keyword this makes data and functionality easily exportable, so they can be passed from one data object to another.
This is why the keyword this is so important in object-oriented programming, where data and functionality concerning a particular process are stored and passed around objects.
For example, the data and functionality could now be combined with data and functionality relating to a user (e.g. name change or login/logout functionality).
In JavaScript classes
In case you are not already familiar with JavaScript classes, they produce new objects. A class a template for the new objects to be produced.
The data to be contained in the new object is specified in a constructor (where it can be defined dynamically) and any functionality is defined below the constructor.
Once a class is defined, a new object can be created using the new
keyword followed by the name of the class, with any data to be used in the new object passed in within parentheses. Below is a class that creates a new user object.
class User { constructor(firstName, lastName) { this.firstName = firstName; // 'this' bind firstName to new object this.lastName = lastName; // 'this' bind lastName to new object } printName(){ console.log(this.firstName + " " + this.lastName); // 'this' refers to binded data } } let user1 = new User("JavaScript", "Developer") user1.printName();
In the context of a class, the keyword this is used to bind data to newly created objects produced by the class. This is the function of the keyword this within the constructor: is it referring to the new object to be produced (its new parent) and attaching this data to it in the process of construction.
In the definition of a function to be included in the new object (specified below the constructor) this refers to the new object and can access any data that has been attached to it within the constructor.
In both instances, the keyword this is referring to what will be the new parent data object produced by the class.
With classes, the use of the keyword this is even more imperative than for a standard object: because classes produce objects with different names, it is imperative to use the this keyword so that the data and functionality works regardless of the name given to an object.
Summary
The this keyword is a versatile way to refer to refer to a parent data object without specifically naming it.
This is useful for exporting data and functionality from one data object to another without it breaking due to a different object name.
As such, the this keyword is an important part of object-oriented programming since it allows data and functionality pertaining to a thing (e.g. a user) or a process to be passed around from one object to another.
Related links
- Turing School of Software and Design: The Four Pillars of Object Oriented Programming
- MDN Mozilla Web Docs: JavaScript Classes