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
thisbinding rules in the right precedence order, and explain why a method loses its binding - Borrow methods with
callandapply, partially apply withbind, and implementbindfrom scratch - Distinguish
__proto__(an object link) from.prototype(a function property) without hesitating - Narrate the four steps
newperforms, and reimplement them - Write classes with fields, statics, accessors and
#privatemembers, and subclass them correctly withsuper - Compose behaviour with mixins, factories and injected dependencies instead of deep class trees
Lessons
- Understanding the this Keyword —
thisis not decided by where a function is written. It is decided by how the function is called. (15 min) - call, apply and bind —
callandapplylendthisfor one call.bindwelds it on for good. (13 min) - 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)
- Constructor Functions —
newis four steps: make an empty object, link it toFn.prototype, runFnwith that object asthis, hand it back unless the function returned an object of its own. (14 min) - 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)
- Inheritance —
extendslinks two chains at once: instances to the parent prototype, and the subclass itself to the parent class.superis how you step back up either one. (16 min) - 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)