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 trialalborz
Full Stack JavaScript Techdegree Graduate 30,885 PointsDoes "this" always create an instance of an object?
Is "this", when used inside of a function, always creating an instance of an object? Is that what makes it a constructor function?
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 Pointsthis
doesn't create an object. It's a reference to an object that already exists, the object whose method you're calling. In the context of a constructor function, this
refers to the instance that you're in the middle of making.
alborz
Full Stack JavaScript Techdegree Graduate 30,885 Pointsalborz
Full Stack JavaScript Techdegree Graduate 30,885 PointsThe object whose method you're calling, or just setting a property, right?
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsI've been pretty deep lately in the ES6 syntax where there is an explicit constructor method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
I'll leave it to someone else to explain how it's actually working under the hood in ES5. But at any rate, it's the
new
keyword that makes a new instance,this
refers to that instance.Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsBrendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsPS Treehouse has a workshop on 'this': https://teamtreehouse.com/library/understanding-this-in-javascript