javascript · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Private fields lock data in; getters let people peek.
Unit 1 hid data in closures. Classes have their own lock: a name starting with # is a . Only code inside the class body can touch #balance. Outside the class, even mentioning it is a SyntaxError.
A , written get balance(), runs when someone reads account.balance, so they can look but not change. Writing to it throws a TypeError in , the careful setting Gwecode always runs your code in. A method, like Account.fromPounds, belongs to the class itself.
class Account {
#balance = 0;
static fromPounds(pounds) {
const account = new Account();
account.deposit(pounds * 100);
return account;
}
deposit(pence) {
if (pence > 0) { this.#balance = this.#balance + pence; }
}
get balance() { return this.#balance; }
}
const savings = Account.fromPounds(12);
console.log(savings.balance, savings); The console shows {} for savings because private fields are never printed or copied.
guess first
A thermostat with a getter. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Thermostat {
#celsius = 20;
get celsius() { return this.#celsius; }
warmer() { this.#celsius = this.#celsius + 1; }
}
const hall = new Thermostat();
hall.warmer();
console.log(hall.celsius);
hall.celsius = 30;
console.log(hall.celsius);
your turn
Your turn. Write a getter for a full name.
Finish the getter so it adds the private last name, then make a customer with a first and last name of your choice.
fix it
The cart count crashes. Can you fix it?
- Look at how
countis defined on line 4. Is it an ordinary method? - A getter is read like a property.
cart.countis already the number 2, and you cannot call a number. - On the last line, change
cart.count()tocart.count, then press run.
nailed it
your classes keep their secrets. :D
- A
#name is a private field, sealed inside the class. - A getter is read like a property, with no brackets.
- Static methods belong to the class, not each instance.
new words in your collection
- private field
- getter
- static
- strict mode
This lesson isn’t saved. A free account remembers every lesson you finish.