What is "this"?

In notebook:
FrontEndMasters Advanced JS fundamentals
Created at:
2015-10-08
Updated:
2015-10-08
Tags:
Fundamentals JavaScript
Learn JS Fundamentals to jQuery & Pure DOM Scripting
> in javascript functions don't know where they live, they only know how they are called

therefore `this` will determined by the call site (how the function is called)

(except for the ES6 Class syntax)

> how the function is what matters not where it is defined

The four rules for determining the call context (​this​)

  1. the [[Call]] operator -> ​this​ will be the ​window​ (if none of the other rules apply)
  2. Dot [[Call]] operator (foo.bar()) -> ​this​ will be set to the left side of the operator
  3. ​new​ keyword (var ​foo = new bar();​) -> ​this​ will be the new object ​foo
  4. ​call​ or ​apply​ (​foo.dosomething.call(bar, "hello");​) -> will be set to the first parameter ​bar​