You already encoutered the this
keyword multiple times in JavaScript. But what does it actually do?
It is a reference to an object and it can reference to different objects, depending where you encouter it. It depends on the context you use it in.
The different contexts are:
- The global context
- A constructor of a class (or a function)
- A method in an object
- In a DOM event handler
Let’s have a closer look at them:
1. The global context
If you run your JavaScript program in a browser, and you are working on the top level, this
will refer to window
.
1
2
3
4
5
console.log(this);
function draw() {
console.log(this);
}
You could for example write this.addEventListener("load", loadHandler);
and it would be the same as window.addEventListener("load", loadHandler);
.
2. A constructor of a class
If you are in the constructor of a class, this
will refer to the object you are creating.
1
2
3
4
5
class Person {
constructor(name) {
this.name = name;
}
}
3. A method in an object
If you are in the method of an object (a function that belongs to an object), this
refers to the object.
1
2
3
4
5
6
7
8
9
10
class Person {
constructor(name) {
this.name = name;
}
getName() {
console.log(this.name);
return this.name;
}
}
4. In a DOM event handler
If you are in a function that is used as an event handler in HTML, this
will refer to the event.currentTarget
, what is usually the object that has fired the event. In this example we use a button in a HTMP page. this
would reference to the HTML element - the button.
1
2
3
4
5
function clickHandler() {
console.log(this);
}
const buttonElement = document.getElementById("button");
buttonElement.addEventListener("click", clickHandler);
Arrow functions
You remember that we talked about arrow functions: () => {}
. These functions are special, because they don’t have their own reference for this
. Instead the use the reference one level up.
Setting the context explicitly
You can set the value of this
explicitly if you need to using the call
, apply
or bind
method. You can learn more about it here;