The code above logs this three times, but what is this?
The main source of confusion is a quirk of the language where depending on the invocation pattern this can be set to the global variable (e.g. window in a browser). But there are come other gotchas.
In the example above this is 3 different objects.
Function Invocation Patterns
I’ve covered the first 3 above in my example
Constructor In this constructor invocation pattern (i.e. new) this is assigned to the object getting created, ATest
In the function invocation pattern this is the enclosing type also, however this is just object in this case i.e. the object literal returned from ATest constructor.
I’m not covering this here but the Apply (and the call) invocation patterns basically let you set the value of this.
Note: Object Literal can be avoided in this example above as follows.
What we do is set the methods on this explicitly.