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 trialJohnny Garces
Courses Plus Student 8,551 PointsWhy did "this" result in the window object when it was logged within a function?
In the video, Huston showed a function that logged this which printed out the global window. Wouldn't it print out the function object since it's wrapped inside a function's execution context?
function helloWorld(){
console.log(this);
console.log('hello world');
}
helloWorld();
OR
function helloWorld(){
var that = this;
console.log(that);
console.log('hello world');
}
helloWorld();
Both functions result in the global object when logging "this"- I thought it would refer to the function object.
Any guidance would be helpful! Thank you
1 Answer
Steven Parker
231,186 PointsIn a global function, "this" would refer to the function's context, which is the window object.
I'm not sure what you mean by "function object". Perhaps you're thinking of a method of an object? In that case, "this" would refer to the object that the method is being called on.
Johnny Garces
Courses Plus Student 8,551 PointsJohnny Garces
Courses Plus Student 8,551 PointsRight- but say there's a nested function
wouldn't the print statement in function b result in the context of function a? Thereby printing out a's function object? (and not the global window?)
Steven Parker
231,186 PointsSteven Parker
231,186 PointsYou might be thinking of "scope". The nested function has a scope provided by the outer function, but they share the same execution context.
There's no actual object associated with a scope.
Johnny Garces
Courses Plus Student 8,551 PointsJohnny Garces
Courses Plus Student 8,551 PointsHere's what I mean re: function object
Johnny Garces
Courses Plus Student 8,551 PointsJohnny Garces
Courses Plus Student 8,551 PointsOh I see- so different scopes (in a nested function) can refer to the same E.context- that's so revealing. Thanks so much, Steven!
Steven Parker
231,186 PointsSteven Parker
231,186 PointsI see, I think of that as just a "variable" or perhaps a "lambda". And I suppose in one sense, everything is an "object". But calling a function does not establish the function itself as an execution context. If it did, you wouldn't have to nest them to see the result.