OOP Studio Ages 9-15
Encapsulation Builder
Students build a backpack object that controls how items are added, used, and shown.
Control an inventory object.
Example code
class Backpack {
constructor(owner) {
this.owner = owner;
this.items = [];
}
addItem(item) {
this.items.push(item);
say(item + " was added to " + this.owner + "'s backpack.");
}
useItem(item) {
let index = this.items.indexOf(item);
if (index === -1) {
say(item + " is not in the backpack.");
} else {
this.items.splice(index, 1);
say(this.owner + " used " + item + ".");
}
}
showItems() {
say("Backpack: " + this.items.join(", "));
}
}
let bag = new Backpack("Milo");
bag.addItem("map");
bag.addItem("snack");
bag.useItem("snack");
bag.showItems();
Program result
- Run your code to see output.
Type real JavaScript, then run it.
Encapsulation builder complete.
You changed inventory data through class methods instead of editing the list directly.
Try Encapsulation Challenge