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 trialColin Sygiel
5,249 PointsCan 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"?
James Reynolds
3,182 PointsI 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
Helmut Granda
10,343 PointsShort answer: scope. this.sum references to the "sum" property of calculator.
Fourteen minute answer: https://teamtreehouse.com/library/understanding-this-in-javascript
Enjoy!
Colin Sygiel
5,249 PointsGracias!
Vishesh Singh
4,332 PointsHi, Please read following articles for a better understanding of this keyword and its usage:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this
http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
https://toddmotto.com/understanding-the-this-keyword-in-javascript/
Tarek Raafat
3,346 PointsBasically, "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"
Randy Eichelberger
535 PointsRandy Eichelberger
535 PointsHere is a good read on "this"
You should spend some time googling around on this because it's a very important thing in JS