javascript · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Closures let you hide data behind a few safe functions.
Any line of code can change a plain object's properties, including a buggy one. A closure can keep a value instead: only the functions made inside the factory can reach it.
Here the factory returns an object holding two functions. They share one hidden balance. The rest of the program must go through them, and deposit can refuse bad amounts. This idea, data plus its guards and nothing else on show, is .
function makeWallet() {
let balance = 0;
return {
deposit(amount) {
if (amount <= 0) { return "Refused"; }
balance = balance + amount;
return "OK";
},
getBalance() { return balance; }
};
}
const wallet = makeWallet();
console.log(wallet.deposit(20), wallet.deposit(-5), wallet.getBalance());
console.log(wallet.balance); Inside an object, deposit(amount) { } is short for deposit: function (amount) { }.
guess first
Someone tries to cheat. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function makeScore() {
let points = 0;
return {
add() { points = points + 10; },
show() { return points; }
};
}
const score = makeScore();
score.add();
score.points = 500;
console.log(score.show());
your turn
Your turn. Guard the muffin stock.
In the first blank, compare against the private stock count so sell refuses big orders. In the second, choose a starting stock of at least 4.
fix it
The coin jar never fills up. Can you fix it?
coins,copies the number into the object once, when the jar is made. Does that copy ever update?- The object needs a function that reads the private
coinsevery time it is asked. - Replace
coins,withcount() { return coins; },and usejar.count()on the last line.
nailed it
your data has a lock on it now. :D
- Variables inside a factory are private to its functions.
- Return only the functions the rest of the program needs.
- Guards inside those functions can refuse bad changes.
new words in your collection
- private
- encapsulation
This lesson isn’t saved. A free account remembers every lesson you finish.