Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRichard Eldridge
8,229 PointsBut why, tho?
So a hint was provided stating to create a variable with the value of this
and use that when calling the updateGameState method. I did that, and it worked. I tried passing this
and it throws an error of updateGameState is not a function.
I expect it has something to do with the context of this
or scope, but I'd like a decent explanation if someone knows.
Thanks!
For reference:
playToken(){
let spaces = this.board.spaces;
let activeToken = this.activePlayer.activeToken;
let targetColumn = spaces[activeToken.columnLocation];
let targetSpace = null;
for(let space of targetColumn){
if(space.token === null){
targetSpace = space;
}
}
if (targetSpace !== null){
const game = this;
game.ready = false;
activeToken.drop(targetSpace, function (){
game.updateGameState(activeToken, targetSpace);
});
}
}
2 Answers
Ashley Boucher
Treehouse TeacherHello!
Your instinct is correct! When you call the drop
method, you're passing in a callback function. This callback function has a different scope than the rest of the content of the Class. If you use the this
keyword inside that callback function, it will no longer be referring to the object.
So, in this case, if you want to access the game inside the callback function (which you've previously been accessing with this
) you have to assign it to a variable.
Hope that helps! Ashley
Von Matterhorn
8,045 PointsAlso as an alternative, you could avoid having to assign this
to a variable if you used an arrow function. This is because arrow functions don't have their own this
. Keep in mind though that arrow functions are ES6 syntax and not supported by all browsers (I'm looking at you at IE).
MDN Reference: Arrow functions
Carlos Chavez
5,691 PointsThis answer! <3
matthewchau2
8,343 Pointsmatthewchau2
8,343 PointsI get this, but then what does the "this" keyword refer to within a callback function?