You’ve finished Objects, this and Classes. Mei’s houseplants started as plain records. Now each one is a Plant that looks after its own data, and a Shelf tells her which ones need water today.
What You Can Do Now
- Model things that hold data and behavior with classes.
- Protect their data with private fields and accessors.
- Predict what
thisrefers to in any call.
Things to Remember
- An ordinary, unbound function gets
thisfrom how it’s called, not where it was written. In a method call such asgoldie.water(),thisis the object before the dot. If you pull the method off withconst water = goldie.waterand callwater()with no dot, then in strict codethisisundefined. - An unbound method passed as a callback loses
this. Inplants.forEach(shelf.waterPlant),waterPlant()loses the shelf, becauseforEachcalls it with no dot. Call it on the object inside a wrapper, as in(plant) => shelf.waterPlant(plant), or bind it. - Arrows take
thisfrom the code around them, so use them for callbacks in methods, not as methods. - The
newkeyword makes an object, runs the constructor withthisas that object, and hands it back. Shared methods live one step up the prototype chain, onPlant.prototype. - Private fields, getters and setters let a class guard its own data. A private field hides the day count. A getter checks whether a plant needs water, and a setter rejects a negative interval.