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.

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
220,364 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
220,364 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
220,364 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".