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 (2015) Practice Project User Interface Code

Linying Wang
Linying Wang
1,479 Points

Why can't I use this.displayNext() within the guessHandler method inside QuizUI?

I used this.displayNext() before instead of QuizUI.displayNext(). but it didn't work. I though this was supposed to refer to the QuizUI? So why I can't do that here?

guessHandler: function(id, guess){
    var button = document.getElementById(id);
    button.onclick = function(){
      quiz.checkAnswer(guess);
      QuizUI.displayNext();
    }

1 Answer

Jesse Mykolyn
Jesse Mykolyn
371 Points

Hi Linying Wang,

Javascript's "this" keyword is a tricky concept, and one which causes all sorts of grief, even for senior developers.

In this case, "this.displayNext()" doesn't work because "this" no longer contains a reference to the QuizUI variable. "This" refers to the object which invokes a particular function, and since the "displayNext()" function is inside the function that's triggered by button.onclick, "this" is actually storing a reference to the button.

You can see this concept at work by replacing the entire "guessHandler()" function with the code block below in your workspace. Alternatively, you can try logging out the "this" keyword at various places in the JS and seeing what it refers to.

guessHandler: function(id, guess) {
    var button = document.getElementById(id);
    console.log('INSIDE guessHandler(), LOGGING OUT this', this);
    button.onclick = function() {
        console.log('INSIDE button.onlick() LOGGING OUT this', this);
        quiz.guess(guess);
        QuizUI.displayNext();
    }
},

Hope that helps!