Because of its uniqueness, it’s no surprise that people are often confused by this mechanism and are not quite sure what
this is going to refer to in a particular case.
However, there are only four rules that compiler follows when resolving the
this reference. For easier remembering, I put them in a sequence of A, B, C, D. The earlier the rule, the bigger importance and priority it has.
If the function was called with the
new keyword, then
this refers to an object constructed using this function.
If the function was bound to a context using the
bind method or was executed using
apply methods, then
this refers to an object passed as an argument to these functions.
If the function called was conatined within an object, then
this refers to the containing object.
If answers to all of the rules above are negative, then
this refers to the global object or to
undefined if strict mode is enabled.
And that’s pretty much it. :) You can check this behavior by yourself, using
a fiddle I’ve created. It contains example code which shows how the
this reference changes according to the mentioned rules.