How do prototypes and classes work?
Practice this questionDefinition:
A prototype is an object from which another object can inherit properties and methods. When a property is missing on an object, JavaScript follows its prototype chain until it finds the property or reaches null. Classes provide structured syntax for constructing objects and sharing methods through that mechanism.
Key points:
-
If a property is missing, JavaScript looks up the prototype chain.
-
Class methods are usually shared through the prototype.
-
Composition means combining small pieces of behavior instead of extending a large parent class.
-
Instance fields belong to individual objects; ordinary class methods are shared through the prototype.
-
A child can override a parent method, but deep inheritance chains can make behavior hard to follow.
Interview point:
- Explain the lookup chain first, then explain class syntax; JavaScript inheritance remains prototype-based.