Underscore convention and closures, compared
The underscore only asks politely. The closure really hides the PIN, but every vault gets its own copy of check; a #pin field gives the same privacy with shared prototype methods.
Names that start with # (like #balance or #validate()) are private: only code written inside that class body can read or change them, and the engine enforces it, so the outside world must go through the methods you choose to make public.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a class Counter with a private #count, methods increment() and reset(), and a getter value. Show that Object.keys(new Counter()) is empty.
Write a class Password that stores a private #hash (use a simple stand-in: the reversed string) set in the constructor, and a method matches(text). It must never expose the stored value.
Add a static method Counter.isCounter(value) to your Counter that uses a brand check and never throws, even for null or 5.
Explain it without notes
What is encapsulation, and how do private fields support it?
How are #private fields different from _underscore properties and from closure variables?
What happens when class code reads obj.#x on an object that isn't an instance, and how do you check safely?
Can a subclass use its parent's private fields? What should it do instead?
Preview
Console
Nothing logged yet.Expected console output
true [ '_pin' ]
true undefined [ 'check' ]