Reputation: 6685
From Javascript-Garden:
Foo.method = function() {
function test() {
//this is set to the global object
}
test();
}
In order to gain access to Foo from within test, it is necessary to create a local variable inside of method that refers to Foo:
Foo.method = function() {
var that = this;
function test(){
//Use that instead of this here
}
test();
}
Could anyone explain this? As far as I understood, this
refers to the global object if it's called in the global scope. But here it's called inside of a function, which is inside a method (first example). Why exactly does it refer to the global object, while the second example doesn't?
Upvotes: 2
Views: 105
Reputation: 94429
The second example uses a closure to place the outer functions variables on the scope chain of the inner function.
Foo.method = function() {
var that = this;
function test(){
//This function has access to the outer variables scope chain.
}
}
Upvotes: 0
Reputation: 943089
As far as I understood, this refers to the global object if it's called in the global scope.
No. this
will refer to the default object if the function is called without explicit context. The scope is irrelevant. (In strict mode it will refer to undefined
instead).
Why exactly does it refer to the global object
We can't tell what it refers to. The value of this
is determined by how the function is called, not how it is defined.
Now you have updated the example, we can see that it is called without context, so this
(in the inner function) will be the default object, which in a web browser is window
(it would be undefined
in strict mode).
while the second example doesn't?
In the second example, the inner function doesn't use this
(which will have the same value as the previous example).
The second example uses that
instead. that
is defined in the scope of the outer function and is set to whatever the value of this
is when that function is called.
Assuming that function is called as Foo.method()
then (outer) this
(and hence that
) will be Foo
because that is the context on which method
was called.
Upvotes: 5
Reputation: 382092
this
in a function isn't set when you define the function. It's only dynamically defined to the receiver of the function call.
If you call foo.test()
, this
in test
will be foo
.
But if you do
var f = foo.test;
f();
then this
in f
(which is foo.test
) will be the external object (window if you're executing it at the root level).
It would be the same with
foo.test.call(window);
Upvotes: 3