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
Benjamin Hedgepeth
5,672 PointsHow is the 'this' keyword used?
I'm having a difficult time understanding how the keyword of 'this' behaves. From what its purpose is, how it is used, and the values that result from it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
2 Answers
Ford Heacock
18,068 PointsHey Benjamin! This is just a shorthand for referring to the current object scope. Or as javascriptissexy.com puts it: "The this reference ALWAYS refers to (and holds the value of) an object—a singular object—and it is usually used inside a function or a method, although it can be used outside a function in the global scope."
For example:
var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
console.log (this.firstName + " " + this.lastName);
}
};
this in this case refers to the scope of the person variable. Replace this with person and you will get the same thing. Hope this helps.
Alexander Davison
65,469 PointsYou can also refer to this workshop: Understanding "this" in JavaScript