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


can you explain me how "this" works(javascript)?

I don't fully understand how it works...

var setAge = function (newAge) { this.age = newAge; }; var bob = new Object(); bob.age = 30; bob.setAge = setAge; bob.setAge(50)

2 Answers

Steven Parker
Steven Parker
230,248 Points

There's an entire 13-minute workshop for Understanding "this" in JavaScript.

The short version is that it stands for the current context. Within an object method, for example, it would represent the object itself. In an event handler, it would be the element that triggered the event.

I realize the short explanation might not be terribly helpful. But you can always watch that video.

Jim Dennis
Jim Dennis
13,075 Points

The JavaScript keyword this refers to the current execution/evaluation context. When defining code after a new operator it refers to the object which is being newly created.

But its semantics are more complicated because of how it can appear in other contexts. Here an explanation of to help with Understanding the "this" keyword in JavaScript.

If you're familiar with Python's use of the "self" parameter then this (in the new context) is similar. But there isn't an equivalent in Python (that I know of) for JavaScript's this as it works in other contexts. Here's a A tour of the differences between JavaScript and Python which touches very briefly on this distinction ... but doesn't go into much detail about the other contexts in which this can be used.