If you have the following code:
var global = this;
function A () {
function B () {
return this;
}
return B();
}
var C = new A();
C === gl
this
has nothing to do with scope, it's not a variable. It's a keyword that evaluates to the currently executing function's object context. The function's object context is determined by how you call it. It doesn't matter where or how the function is defined.
When you call a function like fn()
then it is not in object context and the language wrongly attempts to work around it when it should just throw an error at the mere sight of this
. This is somewhat fixed in strict mode where it would evaluate to undefined
.
When you call a function as a property of some object I.E. obj.fn()
then obj
is bound to this
for that call.
Since it would be clunky having to attach a function to some object just to get the right object context for the call, all functions inherit a .call
method that allows you to specify the object context explicitly:
return B.call(this);