this
keyword is dynamically assigned and determined where it is called from.
There is 4 prioritization on the process of determining this
context.
Is the function called by new keyword? - new binding
var bar = new foo()
Is the function called by .apply or .call? - explicit binding
var bar = foo.call( obj2 )
Is the function called as a method of object? - implicit binding
var bar = obj1.foo()
Global on non strict mode and
undefined
on strict mode.
The other conditions are
- ES6 Arrow functions, this retains the value of the enclosing lexical context's
this
. In global code, it will be set to the global object. - When a function is used as an event handler, its
this
is set to the element the event fired from.