Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is aliasing 'this' in JS so bug prone?

Tags:

javascript

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?

like image 666
Darrell Brogdon Avatar asked Mar 06 '13 18:03

Darrell Brogdon


1 Answers

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.

like image 195
djechlin Avatar answered Oct 14 '22 04:10

djechlin