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

What does 'this' in the code this.style.display = 'none' refer to?

What does this in the code this.style.display = 'none'refer to?

1 Answer

Steven Parker
Steven Parker
231,210 Points

I'd need to see more of the code to be sure, since "this" is context-sensitive. But if this statement was found inside an event handler callback, "this" would refer to the element that triggered the event. So this code would remove that element from the page.

For future questions, show more/all of the code, and include a link to the course page.

Thank you Steven! The question is about this video: https://teamtreehouse.com/library/connecting-with-the-dom-solution

More code here:

const button = document.getElementById('begin-game');

     button.addEventListener('click', ()=>{

        game.startGame();

        this.style.display = 'none';

        document.getElementById('play-area').style.opacity = '1';

});
Steven Parker
Steven Parker
231,210 Points

Hmm, If this handler had been defined with a conventional function, it would represent the (button) element that was clicked.

But since it was defined with an arrow function, and they don't establish "this" like conventional functions do, it would refer to the context that the handler was established in, which looks to be the global context (unless there's other code not shown).

So in that case, "this" would refer to the global context, which certainly doesn't have a "style" property! So I expect this code might cause a TypeError!

Steven Parker
Steven Parker
231,210 Points

Afterthought: you can use arrow functions in handlers by passing in the event object. Example:

button.addEventListener('click', e => {

Then inside the code block you can use "e.target" instead of "this".