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

JavaScript Object-Oriented JavaScript (2015) Introduction to Methods Understanding this

Natalie Cluer
Natalie Cluer
18,898 Points

Not entirely correct?

Andrew states towards the end of the video that "this" refers to the object that "owns" the method where this is called, but this isn't necessarily true is it? "This" refers the the object that invokes the method that contains "this", which is not necessarily the object where it is defined. (In this context it is correct, but this might lead to some confusion down the road when "this" doesn't refer to the expected object)

Steven Parker
Steven Parker
231,268 Points

I'm not sure I understand the distinction you're making between "ownership" and invocation. Could you give examples of each where the difference would be significant?

3 Answers

Steven Parker
Steven Parker
231,268 Points

But In that example, the value of "this" is being explicitly set by the handler mechanism. If you set up the handler this way instead, it will still work as before:

$("button").click(function() { person.sayName(); });  // still says "My name is John"

On the other hand, you can override the value of "this" yourself, too:

person.sayName.call({name: "Fred"});  // says "My name is Fred" !

I'm not sure that the handler's override, or the fact that you can do it yourself, contradicts the point of the lesson.

Natalie Cluer
Natalie Cluer
18,898 Points

Hi Steven! an example would be if a method is passed in as a callback function. In the method, for example : const person = { name: "John", sayName: function () { console.log("My name is " + this.name); // here, "this" refers to the object that "owns" it (Andrew used the word "own in the video") }

but:

$('button').click(person.sayName) // "this" now points to the button object because it was the object that invoked the method, so returns 'cannot read property of undefined'

Natalie Cluer
Natalie Cluer
18,898 Points

got it! thanks! got myself into a bit of a rabbit hole trying to understand "this". i'll keep digging.