In the last video, you read this from the form of a call: the object before the dot, undefined in a strict plain call, the first argument of .call() or .apply(), or the object you bound a function to. Mei now wants a shelf that waters every plant in one go, and that means handing a method to another function.
In this lesson, you’ll pass a shelf’s method to .forEach() the way you’d pass any function, see what happens to this, and fix it two ways. You’ll also be able to choose between them. Start by giving Mei’s plants a shelf.
Hand a Method to .forEach()
A shelf that waters plants needs the plants and a record of what it watered today. Mei wants that record so she can glance at it in the evening and know which plants she’s already seen to.
In your plant-tracker folder, save this as shelf.js. It exports Mei’s four plants and a shelf object with a .waterPlant() method:
shelf.js
export const plants = [
{ name: "Goldie", daysSinceWatered: 6 },
{ name: "Moss", daysSinceWatered: 8 },
{ name: "Lily", daysSinceWatered: 4 },
{ name: "Spike", daysSinceWatered: 21 },
];
export const shelf = {
wateredToday: [],
waterPlant(plant) {
this.wateredToday.push(plant.name);
plant.daysSinceWatered = 0;
},
};
The method reaches the shelf’s list through this.wateredToday, the same way Goldie’s methods reached her data. Check that it works with one plant first. Save this as water.js next to it:
water.js
import { plants, shelf } from "./shelf.js";
shelf.waterPlant(plants[0]);
console.log("Watered today:", shelf.wateredToday);
Run it from the plant-tracker folder:
$ node water.js
Watered today: [ 'Goldie' ]
Goldie is on the list. The call shelf.waterPlant(plants[0]) has shelf before the dot, so this is the shelf.
Now for all four plants. You’ve passed functions to .forEach() before, and shelf.waterPlant is a function, so the natural move is to hand it over as it is. Replace the call to .waterPlant() in water.js so the file reads:
water.js
import { plants, shelf } from "./shelf.js";
plants.forEach(shelf.waterPlant);
console.log("Watered today:", shelf.wateredToday);