Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.6 — Private Fields and Methods
JavaScript · Example 4 of 4

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.

01

Write a class Counter with a private #count, methods increment() and reset(), and a getter value. Show that Object.keys(new Counter()) is empty.

02

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.

03

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

01

What is encapsulation, and how do private fields support it?

02

How are #private fields different from _underscore properties and from closure variables?

03

What happens when class code reads obj.#x on an object that isn't an instance, and how do you check safely?

04

Can a subclass use its parent's private fields? What should it do instead?

Underscore convention and closures, compared

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

true [ '_pin' ]
true undefined [ 'check' ]