Reading Principles of writing consistent, idiomatic JavaScript in the section titled "Faces of this
" it suggests that aliasing this
in JavaScript is "extremely bug prone".
I personally try to use _.bind()
(or something similar) whenever possible but does anyone know why aliasing this
is so error prone?
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.
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.
In plain myFunc()
, this
binds to global object.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With