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) Introduction to Methods Modifying Objects with Methods

Colin Sygiel
Colin Sygiel
5,249 Points

Can someone please re-explain why "this" is used?

In the code the instructor uses "this.sum = ..." but why cannot we just use "sum = ..."? What is the advantage of "this"?

Randy Eichelberger
Randy Eichelberger
535 Points

Here is a good read on "this"

You should spend some time googling around on this because it's a very important thing in JS

James Reynolds
James Reynolds
3,182 Points

I think there are a lot of good answers explaining how to use 'this', but I will try my best to answer why 'this' is used. There may be multiple reasons but as far as I know, a key reason to use 'this' is in case you ever want to change the name of what 'this' is referencing. To use the example from Tarek Raafat, you could achieve the same result by either object.property1 or this.property1. If you don't use 'this' and you imagine that you have a very large object in this case named 'object' and then you decide object is too vague a name I should call it something else. You would have to go through the entire object and change the name every place it occurs. However, if your code uses 'this' it will always refer to the correct object name even if you change that name.

3 Answers

Short answer: scope. this.sum references to the "sum" property of calculator.

Fourteen minute answer: https://teamtreehouse.com/library/understanding-this-in-javascript

Enjoy!

Tarek Raafat
Tarek Raafat
3,346 Points

Basically, "this" refers to the current object for example:

var object = {
      property1: "Something",
      property2: function () {
                       console.log(this.property1);
      }
}

"this.property1" refers to it's current object, and in the above case it's going to be "object.property1"