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

Joseph Michelini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Michelini
Python Development Techdegree Graduate 18,692 Points

When do we need to access .htmlToken and when is using the this keyword enough?

I know this can be tricky, and looking at the code I do understand it but I'm not sure I would know on my own when I had to use the htmlToken getter method to refer to the token I'm using, and when I wouldn't.

Check out the code below:

  moveLeft() {
    if (this.columnLocation > 0) {
      this.htmlToken.style.left = this.offsetLeft - 76;
      this.columnLocation -= 1;
    }
  }

When I'm referencing the columnLocation, because columnLocation is a property of the token class, this refers to the current token. But when I want to update the left position, I need to refer not only to this token but this.htmlToken or "this token with a specific id of...". Why do I need to be more specific in that section of the code, and why is this enough earlier in the function?

Here's the getter method(s) for reference:

  get htmlToken() {
    return document.getElementById(this.id);
  }
  get offsetLeft() {
    return this.htmlToken.offsetLeft;
  }

Thank you!

1 Answer

Steven Parker
Steven Parker
231,141 Points

As you pointed out, "this" refers to the JavaScript object for the token. But the "htmlToken" getter ("this.htmlToken") refers to the HTML element in the DOM that is associated with this object.

So the difference isn't that one is more specific but that they refer to different things. One is the object representation in the code, and the other is the HTML element in the DOM (on the page).