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 Understanding "this" in JavaScript

Why 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
Steven Parker
229,644 Points

In 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.

Right- but say there's a nested function

function a(){

  function b(){
   console.log(this);
  }
   b();
}

a();

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
Steven Parker
229,644 Points

You 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.

Here's what I mean re: function object

function a(){
 console.log('foo');
}

console.log(a); 

Oh 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
Steven Parker
229,644 Points

I 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.