Understanding the this
keyword in JavaScript
An introduction to the this
keyword and how its value is determined in different contexts.
The this
keyword in JavaScript is a core concept of the language and can cause confusion for beginners and more advanced developers alike. In this article, I am going to explain the this
keyword, and its value in different use cases.
What is this?
Every time we run some JavaScript in a web browser, the engine executes multiple steps, one of them being the creation of an execution context. Execution context is an abstract concept, but it refers to the environment in which the code is evaluated and then executed.
Every execution context references an object and that object references the this
keyword. The this
keyword is a reference to the object which called the function. The value of this
, therefore, depends on where it has been used.
Global context
In the global execution context, this
refers to the global object, which in the case of the browser is called window
.
console.log(this === window); // truevar colour = 'red';function getColour() {
var colour = 'purple';
console.log('colour', colour); // colour purple
console.log('this.colour', this.colour); // this.colour red
}getColour();
The getColour()
function is called in the global scope, and the first colour
variable is included in the global scope as well. If we console.log(this)
, the window method has a getColour()
method and a colour
property. When we call this.colour
at this point, it will return red
, but the local variable colour will return purple
.
In this example, this
refers to the window
object so this.colour
refers to the global colour
property.
It’s worth noting that if JavaScript has strict mode enabled then this
in global scope is undefined
.
Object methods
In the instance of creating a new object using a constructor, the this
keyword refers to the new instance of the object.
var firstName = 'Brad';
var lastName = 'Pitt';function User(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.returnName = function() {
return `${this.firstName} ${this.lastName}`;
};
}let newUser = new User('George', 'Clooney');console.log(newUser.returnName()); // George Clooney
When calling the returnUser()
method, this
will reference the newUser
object which was created using the User
constructor. The value will be George Clooney
, not Brad Pitt
, as we are using newUser
object properties.
Inside functions
The use of this
inside function calls can be confusing. A function in JavaScript is an object, it has its own properties and one of them is this
. Its value depends on how it’s invoked.
var dogName = 'Snag';
var dogBreed = 'Dachshund';function getDog() {
return `${this.dogName} the ${this.dogBreed}`;
}var dog = {
dogName: 'Snuffles',
dogBreed: 'French Bulldog',
getDog: function() {
return `${this.dogName} the ${this.dogBreed}`;
}
}console.log('Dog in global scope:', getDog()); // Dog in global scope: Snag the Dachshundconsole.log('Dog in object scope:', dog.getDog()); // Dog in object scope: Snuffles the French Bulldog
In this code there are two functions, one is in the global scope and the other is a dog
object method. When we call the global scope version of getDog()
we use the globally scoped variables Snag
and Dachshund
because the this
keyword in the function refers to the global object. When we call the getDog()
method of the dog
object this refers to the dog
object properties Snuffles
and French Bulldog
.
This demonstrates how we can get two different results using this
in similar functions.
Arrow functions
Arrow functions are an exception to the above rules. They don’t have their own this
. If we reference this
inside of an arrow function it refers to the this
from the outer context.
let user = {
name: 'Mario',
sayHi() {
name: 'Luigi';
let myFunction = () => console.log(`Hi ${this.name}!`);
myFunction();
}
};user.sayHi(); // Hi Mario!
With events
With events, after we trigger an event we call the event handler. When we use the this
keyword in an event handler it refers to the HTML element which triggered the function.
<button class="button myButton">Click</button>const button = document.querySelector('.myButton');button.addEventListener('click', function() {
console.log(this === button); // true
});
Summary
- By default,
this
refers to the global object - In an object method,
this
refers to the object the method was called on - In a function, when JavaScript is not in strict mode,
this
refers to the global object - In a function, when in strict mode,
this
will beundefined
- In an arrow function,
this
retains the value of the enclosing lexical context’sthis
- In a constructor call,
this
is bound to the new object that gets constructed - In an event handler,
this
is bound to the HTML element on which the listener is placed