In this video, you pick up Mei’s shelf where its waterAll() method lost the shelf inside a .forEach() callback. An arrow function fixes it, because an arrow has no this of its own. Then you see why that same fact makes an arrow the wrong choice for a method.
Key Points
- The puzzle:
shelf.waterAll()has the shelf before the dot, so insidewaterAll(),thisis the shelf. But.forEach()calls afunction (plant) { ... }callback plainly, so that function gets its ownthisfrom a plain call:undefinedin strict code.this.waterPlant(plant)then throws aTypeError. - An arrow looks outward: an arrow function doesn’t get a
thisof its own, so no call can fill one in. When it readsthis, it looks outward, to the code it’s written in, the way it finds any variable it doesn’t declare (thoughthisisn’t a variable you can declare or set). - The nearest regular function: the lookup stops at the nearest regular function around the arrow, because every regular function has a
thisof its own. Here, that’swaterAll(), and itsthisis the shelf, sothis.waterPlant(plant)is a method call with the shelf before the dot. This is called lexicalthis. - An arrow’s
thiscomes from the code it’s written in: here, thethisofwaterAll(). Afunctiongets its ownthisfrom how it’s called. - An arrow as a method: writing
waterPlant: (plant) => { ... }in the shelf’s object literal makesthisinside itundefined, even when it’s called asthis.waterPlant(plant)with the shelf before the dot. The arrow takes nothisfrom the call. It looks outward instead, and the braces around the shelf are an object literal, not a function, so they hold nothis. - The module’s top level: the lookup reaches the module’s top level, where you’re outside every function and
thisisundefined. This arrow getsundefinedbecause it was written inside the shelf’s braces but still at the module’s top level, whatever object is before the dot when it’s called. The script stops withTypeError: Cannot read properties of undefined (reading 'wateredToday'). - The fix: write the method with the method shorthand again,
waterPlant(plant) { ... }. That’s why you write methods with the shorthand.
| Where | Write | Example |
|---|---|---|
| A method | the method shorthand | waterPlant(plant) { ... } |
| A callback inside a method | an arrow function | (plant) => { ... } |
A function on its own (no object, so it needs no this) |
a function declaration that takes its record as an argument |
function plantNeedsWater(plant) { ... } |
The rule: an arrow uses the this of the code it’s written in, so inside a method it gets that method’s this. Any other function takes it from the call (or from .bind()).