There are four meanings this
can take dependending on how it was invoked. Accordingly care must be taken to keep track of which this
is being used, and I can think of this
-prone problems in at least 3/4 of them.
Invoked as method
In obj.myFunc()
, this
binds to obj
.
This one can be scary if myFunc
is passed in a callback, as it will forget that it was once part of an object and be invoked standalone. See e.g. What does 'var that = this;' mean in JavaScript? for the usual workaround to this.
Invoked as standalone function
In plain myFunc()
, this
binds to global object.
Invoked as constructor
Invoked as new myFunc()
(very different! All functions that are intended to be invoked with new
should be capitalized, thereby looking like a pseudoclass). Creates a new object, binds it to this
and (probably) returns that object.
Of course if you drop the new
you will bind to the global object, which will likely clobber a lot of stuff and leave your program in a very broken state. The capitalization convention is very important, and lets this problem be picked up by JSLint (IIRC).
Invoked with apply (or call)
Invoked as myFunc.apply(obj, args)
, in which this
binds to obj
. Note this has security implications even, as any caller can swap out this
with its own spoofed object.