Understanding JavaScript’s this keyword

(In Portugese)

The JavaScript this keyword is ubiquitous yet misconceptions abound.

What you need to know
Every execution context has an associated ThisBinding whose lifespan is equal to that of the execution context and whose value is constant. There are three types of execution context: global, function and evaluation. Here’s a tabular summary followed by a little more detail, and some examples:

Execution Context Syntax of function call Value of this
Global n/a global object (e.g. window)
Function Method call:
Function Baseless function call:
global object (e.g. window)
(undefined in strict mode)
Function Using call:
foo.call(context, myArg);
Function Using apply:
foo.apply(context, [myArgs]);
Function Constructor with new:
var newFoo = new Foo();
the new instance
(e.g. newFoo)
Evaluation n/a value of this in parent context

1. Global context
this is bound to the global object (window in a browser)

alert(this); //window

Continue reading