Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

ada harrison
Full Stack JavaScript Techdegree Student 161 PointsQuestion on the event listener on app.js
Hello,
With the event listerner which Listens for click on #begin-game
and calls startGame() on game object. When I use arrow function for the event listener, I get a TypeError that 'this' is undefined
const game = new Game();
/**
* Listens for click on `#begin-game` and calls startGame() on game object
*/
document.getElementById('begin-game').addEventListener('click', () => {
game.startGame();
this.style.display = 'none';
document.getElementById('play-area').style.opacity = '1';
});
BUT when I use the function keyword it works. Please is there any explanation behind this?
const game = new Game();
/**
* Listens for click on `#begin-game` and calls startGame() on game object
*/
document.getElementById('begin-game').addEventListener('click', function(){
game.startGame();
this.style.display = 'none';
document.getElementById('play-area').style.opacity = '1';
});
2 Answers

Martin Zarate
10,723 PointsHere is an explanation on how arrow function binds to "this" https://codeburst.io/javascript-arrow-functions-for-beginners-926947fc0cdc Change "this" to the object itself "document.getElementById('begin-game')" it will work.

ada harrison
Full Stack JavaScript Techdegree Student 161 PointsThanks very much
Dave StSomeWhere
19,822 PointsDave StSomeWhere
19,822 PointsHere's the MDN Explanation