In this video, Mei stops spelling out every plant record by hand. She writes a Plant class in a new file, plant.js, in her plant-tracker folder, and makes Goldie and Moss with new.
You trace, step by step, what new does each time. For now, the plants carry only their data. A function that returns the record could do that too, and the class pays off in the next lesson, when the methods come back.
Key Points
- A class starts with the keyword
classand a name. By convention, class names start with a capital letter, as inPlant, so a class stands out from the objects it makes. - The constructor goes inside the class’s braces. It’s written like a method, but its name is fixed. The
constructorholds the code thatnewruns. Its parameters are the values every plant needs. Each line of its body sets one property onthis. new Plant("Goldie", 5, 6)does three things, in order:- It makes a fresh, empty object.
- It runs the constructor with
thisset to that object, and the values go to the constructor’s parameters. Each line of the body adds a property. - It hands the object back, so
goldierefers to it. The constructor has noreturnof its own, becausenewdoes the handing back. - Node’s output names the class:
console.log(goldie)showsPlant { ... }, and the wordPlantin front names the class that made the object. - Each
newmakes its own object.new Plant("Moss", 7, 3)makes another empty object, separate from Goldie’s, and the constructor fills it with Moss’s values. Changinggoldie.daysSinceWateredleavesmoss.daysSinceWateredalone. newcompletes the call forms forthis:
| The call | this is |
|---|---|
spikeReminder() (bound) |
the object it was bound to |
goldie.reminder() |
goldie, the object before the dot |
reminder() |
undefined (strict code) |
reminder.call(spike), reminder.apply(spike) |
spike, the first argument |
new Plant(...) |
the new object |