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

Question 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

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

Thanks very much