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
Ali A
15,528 PointsWhy I use "this" if I can...
Why I use "this" and I can assign the methods by function for example
var Portland = {
bridges: 12,
airport: 1,
soccerTeams: 1,
logNumberOfBridges: function() {
console.log("There are " + Portland.bridges + " bridges in Portland!, and " + Portland.airport + " Airport")
}
}
Portland.logNumberOfBridges();
1 Answer
Steven Parker
243,656 PointsReferring to itself by name inside an object can make your code "brittle" and subject to errors. Imagine, for example, if the following were added to the code above:
var city = Portland;
Portland = "not an object";
city.logNumberOfBridges();
But if "this" is used inside the object instead of "Portland", it would still work just fine.
Ali A
15,528 PointsAli A
15,528 PointsRight, That makes sense. Thank you a lot, Steven.