The biggest JavaScript OOP gotcha: the 'this' keyword
Object Oriented programming is very straightforward for most OOP languages but JavaScript is a bit different.
Given a game creator function, we want to extend the game
object so it has some additional methods to increment the score game.scorePoint()
.
You can use es6console to run our experiments.
Let's see the code:
function GameCreator(score) {
this.score = score;
}
GameCreator.prototype.scorePoint = function() {
function incrementScore() {
this.score++;
}
incrementScore();
};
GameCreator.prototype.endGame = function() {
console.log(`Game has finished ${this.score}`)
};
let game = new GameCreator(0);
game.scorePoint();
After executing this code, you will notice that game.score
is still 0
. But Why? What happened? Is our code wrong?
Yes it's wrong (but it looks fine, right?). First let's understand why it's wrong. Turns out this
from this.score++
represents the window
object not the game
instance. HA! Gotcha! That means our score
is somewhere lost in the window
.
So, the idea with this example is to understand that a nested function will not look up for the instance, in our case the game
instance. Imagine for a moment that scorePoint
not only has incrementScore
but also printScore
. But hey, why not also another function endGameWhenMaXScore
? See? The function could be split into small ones which is something great, since it helps to organize the code, each function is reponsible for one little thing.
Now to fix the issue... we can use Arrow Functions:
function GameCreator(score) {
this.score = score;
}
GameCreator.prototype.scorePoint = function() {
const incrementScore = ()=> {this.score++};
incrementScore();
};
GameCreator.prototype.endGame = function() {
console.log(`Game has finished ${this.score}`)
};
let game = new GameCreator(0);
game.scorePoint();
By using the Arrow Function
we are indicating that we want to use the game
instance instead of window
.
Now game.score;
will return 1
.
Using the constructor method:
function GameCreator(score) {
constructor (score) {
this.score = score;
}
increment() {
this.score++;
}
endGame(){
console.log(`Game has finished ${this.score}`)
}
}
let game = new GameCreator(0);
game.increment();
game.endGame();
Using ES6 classes Classes - JavaScript | MDN:
class Game {
constructor (score) {
this.score = score;
}
increment() {
this.score++;
}
endGame(){
console.log(`Game has finished ${this.score}`)
}
}
let game = new Game(0);
game.increment();
game.endGame();
See the code running here
Isn't it pretty? I like it, you like it, everybody does.
So, we have learn that while this
can be very tricky, it is still manageable. You just need to understand this
in each context.
Try experimenting with the this
keyword in different contexts and analyze the results. It will help you understand how it works. At the end you will avoid a lot of mistakes and you will become a better JS developer!
Latest Articles by Our Team
Our expert team of designers and developers love what the do and enjoy sharing their knowledge with the world.
-
No app left behind: Upgrade your application to Ruby 3.0 and s...
-
A look forward from 2020
-
Testing Rails applications on real mobile devices (both design...
We Hire Only the Best
reinteractive is Australia’s largest dedicated Ruby on Rails development company. We don’t cut corners and we know what we are doing.
We are an organisation made up of amazing individuals and we take pride in our team. We are 100% remote work enabling us to choose the best talent no matter which part of the country they live in. reinteractive is dedicated to making it a great place for any developer to work.
Free Community Workshops
We created the Ruby on Rails InstallFest and Ruby on Rails Development Hub to help introduce new people to software development and to help existing developers hone their skills. These workshops provide invaluable mentorship to train developers, addressing key skills shortages in the industry. Software development is a great career choice for all ages and these events help you get started and skilled up.