Command Palette

Search for a command to run...

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

Reading a private field from the wrong object

Code inside the class may read #code on any Secret. A look-alike object or a Proxy wrapper isn't a real instance, so the read throws.

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?

Reading a private field from the wrong object

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

42
true
TypeError: Cannot read private member #code from an object whose class did not declare it
through a Proxy: TypeError