Objects, prototypes and classes · mid
Classes: fields, #private, static and super
A class is a special constructor with a strict-mode body, methods on the prototype, per-instance fields, real privacy with #names, static members on the class itself and super for calling the parent — more than syntax sugar.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Differences from constructor functions: the body is strict; class declarations are in the TDZ until defined; calling without new throws; methods are non-enumerable; extends links both the instance chain and the static chain.
- Fields (x = 1) are created on each instance; in a derived class they are added right after super() returns. Methods live on the prototype.
- #private fields and methods are enforced by the engine. #x in obj is a brand check. They are invisible to Object.keys, JSON.stringify and Proxy.
- A derived constructor must call super() before using this, otherwise ReferenceError.
- static methods and fields live on the class; static { } blocks run setup once; this inside a static method is the class.
- TypeScript private is erased at compile time; #private exists at runtime.
- Trap: if a base constructor calls a method that the child overrides, the child's fields are not initialised yet at that moment.
The red pen
Common traps: mistake → fix
Mistake: Classes are just sugar
Fix: strict mode, TDZ, new-only calls, non-enumerable methods, super and #private are real differences.
Mistake: TypeScript private is private at runtime
Fix: it is erased; use #private.
Mistake: Fields live on the prototype
Fix: fields are per instance; methods are on the prototype.
Easy to hard
Questions interviewers ask, easy to hard
- ES classes vs ES5 constructor functions: what is really different?
- What are class fields and #private? How is #private different from TypeScript private?
- Why must you call super() before using this?
- When are static members and static blocks useful?
- Explain the base-constructor-calls-overridden-method field initialisation trap.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.