Objects, Classes and this
Give objects their own functions, find out what this points to and why it sometimes gets lost, then build objects from classes with private fields, getters, setters and inheritance, and see the prototypes underneath.
Updated
this in JavaScript
- Methods and this (Apprentice): A method is a function that belongs to an object, and inside it the word this means the object before the dot, so one method can work on whichever object calls it.
- Losing this, and How Arrow Functions Help (Journeyman): When you hand a method to other code as a callback, it loses the object before the dot and this goes missing, and an arrow function or bind gives it back.
Classes in JavaScript
- Classes: Blueprints for Objects (Apprentice): A class is a blueprint for objects of one kind, with a constructor that fills in each new object and methods they all share, and new builds an object from it.
- Private Fields, Getters and Setters (Journeyman): A private field keeps an object's data out of reach of other code, a getter lets that code read it, a setter checks a new value before storing it, and static members belong to the class itself.
- Inheritance with extends and super (Journeyman): A class that extends another starts with everything the parent has, calls super to let the parent set up its part, and can add methods or override the parent's with its own version.
- Prototypes: What Classes Are Made Of (Freelancer): Underneath every class, each object is linked to a prototype object that holds the shared methods, and JavaScript finds a property by walking that chain of links until it finds it or runs out.
Exercise: Space Fleet
- Exercise: Space Fleet (Journeyman): Finish the classes behind a space shooter's fleet, a Ship with private shields, a Fighter that extends it and a Fleet that reports who can fly, and let the tests check each one.