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 Making the Game Interactive handleKeydown() Solution

Scott McInnis
Scott McInnis
8,758 Points

Callback without anonymous function wrapper

How would the callback function differ without the anonymous function wrapper since the handleKeydown method is already set to accept the event object directly?

How does the scope of the callback change?

i.e., would the following still work?

document.addEventListener('keydown', game.handleKeydown);

3 Answers

Steven Parker
Steven Parker
231,271 Points

You might have a problem with the calling context if you don't use the wrapper. The method expects "this" to refer to the Game object, which it will if called in the wrapper. But if you use it directly as the callback, "this" will refer to the document object instead.

Scott McInnis
Scott McInnis
8,758 Points

Thanks Steven, that makes perfect sense! For anyone interested, the lesson on js closures helped explain the method scope in a very clear manner.

When I first coded this part, I did this passing the game.handleKeydown directly as shown in your example. I kinda understand Steven Parker explanation, but not completely. It is not clear to me why this would reference the event target instead of the game object. I think this is something very important to pay attention to.

Tim Oltman
Tim Oltman
7,730 Points

I had this problem. I wrote the following code in my app.js file:

document.addEventListener('keydown', game.handleKeydown)

Then in my game.handleKeydown function 'this' referred to the document, not 'game'!

Steven Parker
Steven Parker
231,271 Points

That's exactly what Scott's question is asking about.