this, Prototypes and Classes

The four rules that decide what this is, how to force it with call, apply and bind, the prototype chain every object secretly walks, what new really does, and how classes are a readable spelling of all of it. Ends with the composition patterns that let you stop reaching for inheritance.

What you will be able to do

  • Apply the four this binding rules in the right precedence order, and explain why a method loses its binding
  • Borrow methods with call and apply, partially apply with bind, and implement bind from scratch
  • Distinguish __proto__ (an object link) from .prototype (a function property) without hesitating
  • Narrate the four steps new performs, and reimplement them
  • Write classes with fields, statics, accessors and #private members, and subclass them correctly with super
  • Compose behaviour with mixins, factories and injected dependencies instead of deep class trees

Lessons

  1. Understanding the this Keyword — this is not decided by where a function is written. It is decided by how the function is called. (15 min)
  2. call, apply and bind — call and apply lend this for one call. bind welds it on for good. (13 min)
  3. Prototypes — Every object holds a hidden link to another object. A failed property lookup follows that link, over and over, until it reaches null. (16 min)
  4. Constructor Functions — new is four steps: make an empty object, link it to Fn.prototype, run Fn with that object as this, hand it back unless the function returned an object of its own. (14 min)
  5. Classes — A class is a readable spelling of a constructor function plus its prototype, with a few rules that make the sloppy versions impossible. (18 min)
  6. Inheritance — extends links two chains at once: instances to the parent prototype, and the subclass itself to the parent class. super is how you step back up either one. (16 min)
  7. Composition over Inheritance — Inheritance says what a thing is, and you get one answer forever. Composition says what a thing has, and you can pick a different set for every object. (14 min)