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 trial

JavaScript Object-Oriented JavaScript: Challenge Adding the Game Logic Callback Function Solution

Richard Eldridge
Richard Eldridge
8,229 Points

But 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.


For reference:

        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
Ashley Boucher
Treehouse Teacher


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

I get this, but then what does the "this" keyword refer to within a callback function?

Also 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

This answer! <3