I was reading Angus Croll understanding JS this blog and found this
var a = {
b: function() {
var c = function() {
return this;
};
return c();
}
};
a.b();//window
To me it looks like, at the time of invoking c, c was inside b. that should be the invoking context (correct me, if i am wrong). when it executes, Why context(this) of c() is window?
there is another example i found in that blog
var a = {
b: function() {
return (function() {return this;})();
}
};
a.b(); //window
why context of b is window? Does anonymous function always run in the global context?
Here's a good way to understand
this(pun intended):The value of
thisinside a function is determined by the way the function is called. With one exception, it doesn't have to do with where the function is defined, what other functions it may be nested inside, what object it was defined as part of, what kind of function it is, or any of that.When you call a function using a method call like
foo.bar()orfoo[bar](),thisinside the function is thefooobject.When you call a function with an ordinary function call like
foo(),thisin the function is thewindowobject, or if the function uses strict mode it isundefined.That's the one exception - if the function itself or its surrounding code has
"use strict";it changesthisfor a plain function call. For good code that shouldn't make a difference - you shouldn't be writing code that depends onthisbeing thewindowobject anyway.Otherwise, what you care about is what object
thisrefers to in a method call. And that's always determined by how the function is called, not how it's defined.Let's go through your first example.
When you call
a.b(), you're callingbas a method of theaobject. So inside thebfunction,thisis the same asa.As it happens, it doesn't do us any good to know that, because the
bfunction never does anything withthis. All it does is callc()as an ordinary function. So insidec,thisis thewindowobject, or it would beundefinedif you were in strict mode.The
cfunction simply returns itsthisvalue, orwindow. And that is also the return value fromb. So that's why you seewindowas the result: it all comes from how the code calls thebandcfunctions.Now about the second example: well, that's just terribly obfuscated code, isn't it? Who would ever write this code and expect anyone to understand it at first glance?
So let's turn it into a more readable form. This line is the problem:
Let's take out the parenthesized function expression:
and assign it to a temp variable:
We don't need the extra parentheses any more, and let's indent the code for readability:
and we can call that
tempvariable as a function in thereturnstatement:Now we can put this back into the
bfunction in the code example:Hey! Doesn't that code look familiar? In fact, it's identical to the first example except for the name of the
tempvariable. So now you see why it works the same as the first one.