Encapsulation
Students keep important data inside an object and use methods to change it safely.
Encapsulation
Encapsulation puts the object's data in a protective case with rules on the door. Nobody sets the player's health directly — they ask takeDamage(), and the method enforces the rules, like "health never drops below zero."
-
1
Data lives inside the case
this.healthbelongs to the Player object. The rest of the program shouldn't reach in and scribble on it — that's how impossible values like -50 health sneak into games. -
2
Methods are the only door
takeDamage(amount)changes health and enforces the rule:if (this.health < 0) this.health = 0;No matter who calls it or how hard the hit, the rule always runs. -
3
Try it
Call
takeDamage(99)and check the health — it stops at 0, never goes negative. Add aheal()method with its own rule: never above 10.
Protect object data with methods.
class Player {
constructor(name) {
this.name = name;
this.health = 10;
}
takeDamage(amount) {
this.health -= amount;
if (this.health < 0) {
this.health = 0;
}
}
heal(amount) {
this.health += amount;
if (this.health > 10) {
this.health = 10;
}
}
status() {
say(this.name + " has " + this.health + " health.");
}
}
let hero = new Player("Nova");
hero.takeDamage(3);
hero.heal(1);
hero.status();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
You used methods to protect and update an object property in a controlled way.
Open Encapsulation Builder