16
What Does "this" Refer to in JS?
JS's "this" keyword has always caused a lot of confusion for me because it was difficult to understand what it referred to. I will attempt to clear this confusion up for myself and for anyone else reading.
The most important thing we have to remember is that "this" differs according to how a function is called. There are 4 main ways you can call a function which will help us understand how "this" works.
You can call a JS function:
- as a function
var age = 100;
function foo () {
var age = 10;
console.log(this.age);
}
foo(); // PAY ATTENTION HERE. This part determines what "this" will refer to.
Here, foo() is 100. In this situation, "this" refers to the global object because the function is called as a regular function and all regular functions refer to the global object(window).
- as a method
var age = 100;
var player = {
name: 'Joe',
age: 35,
foo: function () {
console.log(this.age)
}
}
player.foo(); //PAY ATTENTION HERE. This part determines what "this" will refer to.
Here, player.foo() is 35. In this situation, "this" refers to the the player object because foo() is called as a method attached to player.
- as a constructor
function Foo (name) {
this.name = name;
console.log(this);
}
var player = new Foo('joe') // PAY ATTENTION HERE. This part determines what "this" will refer to
For constructor functions, a new "this" is created each time and that is what it refers to. So, the "this" in the code example above would refer to the variable "player". You should try console.log and see what you get. You will most likely get {name: 'joe'}.
- via apply, call, and bind
let player1 = {
name: 'joe',
age: 35,
printName: function () {
console.log(this.name);
}
}
let player2 = {
name: 'paul',
age: 30,
}
player1.printName() // 'joe'
player1.printName.call(player2); // 'paul'
We learned that when a function is called as a method, "this" refers to the object it is attached to. But in player1.printName.call(player2), "this" refers to player2 instead of player1. This is possible because of call. With call you can decide what "this" will refer to. It is the same with apply and bind but I won't go into the details in this post.
16