Private fields
JavaScript · Unit 14: Modern classes
- Full plan
- JavaScript
- 10 exercises
A value that starts out the same in every object can be declared right in the class body, with no constructor: count = 0;. Every new object starts with its own copy.
class Counter {
count = 0;
up() {
this.count++;
}
}
const c = new Counter();
c.up();
c.up();
console.log(c.count);Prints
2
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
Two boxes are created and only one gets something. What does it print?
2. Complete the code
Fill in the field declaration so the flask starts at 0 ml.
3. Predict the output
What does this code print?
4. Predict the output
Look closely at the name on the last line. What does it print?
5. Find the bug
This program should print 50, the money in the account. Which line has the error?
6. Complete the code
Fill in the declaration so the chest's coins can only be touched from inside.
7. Multiple choice
The
Accountclass keeps its money in#balanceand only moves it withdepositandwithdraw. What does that buy you?8. Put the lines in order
Put the
Piggyclass in order: it keeps its coins private and lets you see them through aget.9. Find the case that fails
enroll(times)signs that many people up for a workshop with 3 spots and returns how many spots are left, which can never be less than 0. Which call does it fail on?10. Predict the output
The report has a
get points, but noset. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.