Mei has four houseplants and a Node.js script that knows about them. Goldie the pothos wants water every 5 days, Moss the monstera every 7, Lily the peace lily every 4, and Spike the cactus every 21. Right now, each plant is a plain record, and the code that looks after them lives in separate functions that take a record as an argument.
In this lesson, you’ll move that behavior into the plants themselves. You’ll turn standalone functions into methods, use this to let a method read and update its own plant, and predict which object this refers to in a call. Start with the script as you’d write it today.
Store a Function on the Plant
The problem with separate functions is that the data and the code that works on it drift apart. Every call has to hand the right record to the right function, and nothing on the record tells you which functions belong to it.
If you don’t have a folder for the tracker yet, create one and move into it:
$ mkdir plant-tracker
$ cd plant-tracker
Then add a package.json file to the folder, so Node.js treats your .js files as ES modules, JavaScript files that can share code through import and export:
package.json
{
"type": "module"
}
Now save this as plants.js. It holds two of Mei’s plants and the two functions you’d write with what you know so far:
plants.js
const goldie = { name: "Goldie", waterEveryDays: 5, daysSinceWatered: 6 };
const moss = { name: "Moss", waterEveryDays: 7, daysSinceWatered: 3 };
function plantNeedsWater(plant) {
return plant.daysSinceWatered >= plant.waterEveryDays;
}
function waterPlant(plant) {
plant.daysSinceWatered = 0;
}
console.log("Goldie needs water:", plantNeedsWater(goldie));
waterPlant(goldie);
console.log("Goldie needs water:", plantNeedsWater(goldie));
console.log("Moss needs water:", plantNeedsWater(moss));
Run it from the plant-tracker folder:
$ node plants.js
Goldie needs water: true
Goldie needs water: false
Moss needs water: false
Goldie starts out overdue, so waterPlant() resets her count to 0, and the second check says she’s fine. The script works, so the open question is where those functions should live.
You already know that a function is a value. You can store it in a variable, so you can also store it in an object’s property. A function stored in a property is called a method, and you call it with a dot, as in goldie.needsWater(). You’ve been calling methods all along, since console.log() is the log method of the console object.
JavaScript has a short form for writing methods, the method shorthand. Instead of needsWater: function () { ... }, you write the name, the parentheses, and the body:
const goldie = {
name: "Goldie",
needsWater() {
// ...
},
};
That leaves one question for the method’s body. How does it reach Goldie’s data when there’s no plant parameter anymore?
Reach the Plant’s Data Through this
A method needs a way to say “the object I was called on.” You could write goldie.daysSinceWatered inside the method, but then the method only works for Goldie, and Moss would need a copy that names moss. JavaScript gives every method call a keyword for this job, called this.
When you call goldie.needsWater(), this inside .needsWater() refers to goldie, the object before the dot. Replace plants.js with a version where Goldie carries her own methods:
plants.js
const goldie = {
name: "Goldie",
waterEveryDays: 5,
daysSinceWatered: 6,
needsWater() {
return this.daysSinceWatered >= this.waterEveryDays;
},
water() {
this.daysSinceWatered = 0;
},
};
console.log("Goldie needs water:", goldie.needsWater());
goldie.water();
console.log("Goldie needs water:", goldie.needsWater());
console.log("Days since watered:", goldie.daysSinceWatered);
Each plant. from the old functions becomes this., and the plant parameter is gone. Run the script again:
$ node plants.js
Goldie needs water: true
Goldie needs water: false
Days since watered: 0
The two checks of Goldie give true, then false, as before. .needsWater() reads Goldie’s state through this, and .water() changes it. Because this is the same object that goldie refers to, the update shows up when you read goldie.daysSinceWatered afterward.
Try breaking it on purpose: change waterEveryDays to 10 and run the script again. The first line now says false, because the method always reads the current data of the object it’s called on.
Writing the same methods out again for all four plants would be clumsy, and each record would get its own function. Later in this course, you’ll use classes to let every plant share one set of methods. For now, one plant with its own methods is enough to see how this works.
If it isn’t clear yet how this gets from the method to Goldie’s numbers, ask the AI mentor. The button below opens a chat with the mentor, with a question already typed in for you to send or change. Ask it to trace one call, such as goldie.needsWater(), step by step, and follow up with whatever still puzzles you.
Find this Before the Dot
Mei’s partner Ravi has a spider plant called Sunny, and he’d like the same check. Does a method written inside goldie always answer about Goldie? The quickest way to find out is to step out of the script and into the Node.js REPL, an interactive prompt for running JavaScript. Start it with node in your terminal, and type this session:
> const goldie = {
… waterEveryDays: 5,
… daysSinceWatered: 6,
… needsWater() {
… return this.daysSinceWatered >= this.waterEveryDays;
… },
… };
undefined
> const sunny = { waterEveryDays: 3, daysSinceWatered: 1 };
undefined
> sunny.needsWater = goldie.needsWater;
[Function: needsWater]
> sunny.needsWater === goldie.needsWater
true
> goldie.needsWater()
true
> sunny.needsWater()
false
The line sunny.needsWater = goldie.needsWater doesn’t copy the method. It stores the same function in a second object, and === confirms there’s only one function. Yet the two calls give different answers. Goldie, at 6 days of 5, needs water. Sunny, at 1 day of 3, doesn’t.
The function has no fixed owner. The value of this depends on how you call the function, not where you write it: in sunny.needsWater(), the object before the dot is sunny, so this is sunny.
If it still feels odd that one shared function answers about two different plants, ask the mentor below to compare the two calls with you. Then type .exit to leave the REPL and go back to plants.js.
Objects can also hold other objects, and that gives a call more than one dot. Give Goldie in plants.js a pot property below .water(), holding an object with its own data and its own method. Keep her two methods as they are, and set waterEveryDays back to 5 if you changed it to 10. Then replace the last console.log() line, the one that prints the days since watered, with a line that describes the pot. The whole file now looks like this:
plants.js
const goldie = {
name: "Goldie",
waterEveryDays: 5,
daysSinceWatered: 6,
needsWater() {
return this.daysSinceWatered >= this.waterEveryDays;
},
water() {
this.daysSinceWatered = 0;
},
pot: {
material: "terracotta",
sizeInches: 6,
describe() {
return `${this.sizeInches}-inch ${this.material} pot`;
},
},
};
console.log("Goldie needs water:", goldie.needsWater());
goldie.water();
console.log("Goldie needs water:", goldie.needsWater());
console.log("Goldie's pot:", goldie.pot.describe());
Before you run it, predict what the last line prints. There are two objects in goldie.pot.describe(), and this can only be one of them.
$ node plants.js
Goldie needs water: true
Goldie needs water: false
Goldie's pot: 6-inch terracotta pot
Goldie’s own methods still answer about Goldie, and this in .describe() is the pot, not Goldie. The rule is to look at the object before the last dot, the one right in front of the method. goldie.pot is evaluated first and gives the pot object, and then .describe() is called on it. If this were goldie, both this.sizeInches and this.material would be undefined, because Goldie has neither property.
An arrow function stored as a method doesn’t follow this rule. You’ll see why later in this course, so write your methods with the shorthand for now.
Check Your Understanding
Use these questions to check that you can predict a method call and write a method of your own:
- Moss is stored as
{ name: "Moss", waterEveryDays: 7, daysSinceWatered: 8 }plus the same.needsWater()and.water()methods as Goldie. What doesmoss.needsWater()return before and aftermoss.water()? - Suppose the REPL’s
goldiealso has the.water()method from the second version ofplants.js. Ravi runssunny.water = goldie.waterand thensunny.water(). WhosedaysSinceWateredchanges? - Lily has a pot of her own,
lily.pot, with the same.describe()method. Inlily.pot.describe(), what doesthisrefer to? - Turn this standalone function into a method of
goldiecalled.label():
function plantLabel(plant) {
return `${plant.name}, every ${plant.waterEveryDays} days`;
}
- It returns
truebefore, since 8 days is at least 7, andfalseafter, because.water()setsthis.daysSinceWatered, which is Moss’s count, to0. - Sunny’s
daysSinceWateredchanges. The call issunny.water(), sothisissunny, and Goldie’s count stays as it was. thisrefers to the pot. The object before the last dot islily.pot, notlily.- Each
plant.becomesthis., and the parameter goes away:
const goldie = {
name: "Goldie",
waterEveryDays: 5,
label() {
return `${this.name}, every ${this.waterEveryDays} days`;
},
};
console.log(goldie.label());
Running it prints the label from Goldie’s own data:
Goldie, every 5 days
Your plant can now look after its own data, and you can tell which object this refers to when you call a shorthand method with a dot. That leaves calls with no dot at all. What this refers to in those calls depends on a setting your module has been using all along, and the next lesson, Run Your Code in Strict Mode, shows you what that setting is.