Methods Change State
Students learn that methods can change an object's internal values, like energy, score, or health.
Methods change state
An object remembers its own facts — that memory is called state. A method is an action that can change that state: every time the robot pet plays, its energy battery drains by one.
-
1
State = the object's memory
this.energy = 3in the constructor gives every new pet a full battery. That number lives inside the object and sticks around between actions. -
2
Methods update it:
this.energy = this.energy - 1Each
play()call reads the pet's own energy, subtracts one, and saves it back. Call it three times and the battery hits zero — the object remembered every play. -
3
Try it
Add a
recharge()method that setsthis.energy = 3again, then play, recharge, and play some more. You're managing state — the heart of every game.
Change a property with a method.
class RobotPet {
constructor(name) {
this.name = name;
this.energy = 3;
}
play() {
this.energy = this.energy - 1;
say(this.name + " played. Energy: " + this.energy);
}
}
let pixel = new RobotPet("Pixel");
pixel.play();
pixel.play();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
You called a method that changed the object's energy property.
Open State Builder