In the last video, Mei wrote a Plant class and made Goldie and Moss with new. Each plant holds its own data now, but it can’t do anything yet. Back in the first lesson, Goldie’s object carried its own .needsWater() and .water() methods, and writing those out again for every plant would have been clumsy.
In this lesson, you’ll give the Plant class its methods, so every plant it makes can check and update itself. You’ll make all four of Mei’s plants, keep them in a list, and see how a class compares with the object literals and factory functions you already write. Start by putting the methods where every plant can reach them.
Give the Class Its Methods
A class can hold more than a constructor. Every method inside its braces is written once and shared, so every plant the class makes can call it.
As a reminder from the last video, new Plant(...) makes a new object, runs the constructor with this set to that object, and hands the object back. An object made this way is called an instance of the class, so Goldie is an instance of Plant.
Open plant.js in your plant-tracker folder, or create it, and replace its contents with this version. The constructor is the one from the video. Below it come three methods, and export in front of class lets other files import the class:
plant.js
export class Plant {
constructor(name, waterEveryDays, daysSinceWatered) {
this.name = name;
this.waterEveryDays = waterEveryDays;
this.daysSinceWatered = daysSinceWatered;
}
needsWater() {
return this.daysSinceWatered >= this.waterEveryDays;
}
water() {
this.daysSinceWatered = 0;
}
addDay() {
this.daysSinceWatered += 1;
}
}
The methods use the shorthand you met in the first lesson, and they reach the plant’s data through this. .needsWater() and .water() are Goldie’s original methods. .addDay() is new, because Mei’s tracker needs each count to grow by one as a day goes by.
Watch out for how a class body differs from an object literal. A class body has no commas between its methods, no name: value pairs, and no function keyword. Any of those stops Node.js with a SyntaxError before your code runs.
Now try the methods out. Save this as today.js next to plant.js:
today.js
import { Plant } from "./plant.js";
const goldie = new Plant("Goldie", 5, 6);
const moss = new Plant("Moss", 7, 3);
console.log("Goldie needs water:", goldie.needsWater());
goldie.water();
console.log("Goldie needs water:", goldie.needsWater());
console.log("Moss needs water:", moss.needsWater());
const shared = goldie.needsWater === moss.needsWater;
console.log("Same function:", shared);
Run it from the plant-tracker folder: