Consider the following code:
function A() {}
A.prototype.go = function() {
console.log(this); //A { go=function()}
var f = function() {
console.log(this); //Window
};
f();
}
var a = new A();
a.go();
Why does 'this' inside function 'f' refers to the global scope? Why it is not the scope of function 'A' ?
The scope of all functions is
window
.To circumvent that, you can do this:
The reason why is you are invoking
f
as afunction
and not amethod
. When invoked as a functionthis
is set towindow
during the execution of the targetBecause function
f()
is not called without any object reference. Try,JavaScript has a different concept of what the special name
this
refers to than most other programming languages do. There are exactly five different ways in which the value ofthis
can be bound in the language.The Global Scope
When using
this
in global scope, it will simply refer to the global object.Calling a Function
Here,
this
will again refer to the global object.Calling a Method
In this example,
this
will refer totest
.Calling a Constructor
A function call that is preceded by the
new
keyword acts as a constructor. Inside the function,this
will refer to a newly createdObject
.Explicit Setting of
this
When using the
call
orapply
methods ofFunction.prototype
, the value ofthis
inside the called function gets explicitly set to the first argument of the corresponding function call.As a result, in the above example the method case does not apply, and
this
inside offoo
will be set tobar
.Common Pitfalls
While most of these cases make sense, the first one is to be considered another mis-design of the language because it never has any practical use.
A common misconception is that
this
inside oftest
refers toFoo
; while in fact, it does not.In order to gain access to
Foo
from withintest
, it is necessary to create a local variable inside ofmethod
which refers toFoo
.that
is just a normal variable name, but it is commonly used for the reference to an outerthis
. In combination with closures, it can also be used to passthis
values around.Assigning Methods
Another thing that does not work in JavaScript is function aliasing, which is assigning a method to a variable.
Due to the first case,
test
now acts like a plain function call; therefore,this
inside it will no longer refer tosomeObject
.While the late binding of
this
might seem like a bad idea at first, in fact, it is what makes prototypal inheritance work.When
method
gets called on a instance ofBar
,this
will now refer to that very instance.Disclaimer: Shamelessy stolen from my own resources at http://bonsaiden.github.com/JavaScript-Garden/#function.this