Study notes · 12% of the exam

this and Binding

`this` is decided by how a function is called, except in arrow functions, which inherit it.

Key points

  1. 1

    Method call obj.fn() sets this to obj. A plain call fn() sets it to undefined in strict mode (modules and classes are always strict).

  2. 2

    call and apply invoke immediately with a chosen this; bind returns a new function with this fixed.

  3. 3

    Arrow functions have no this of their own; they use the surrounding scope's, so they suit callbacks inside methods.

  4. 4

    new Fn() creates a fresh object and binds this to it.

Common traps

  • Passing obj.method as a callback (to setTimeout or an event listener) loses this unless you bind it or wrap it in an arrow function.

Test yourself on this and Binding

Ten questions, with the answer and explanation after each one.