Problem Statement
Explain prototypal inheritance in JavaScript. How does it differ from classical inheritance?
Explanation
JavaScript uses prototypal inheritance, which is fundamentally different from classical inheritance used in languages like Java or C++.
Prototypal inheritance:
Objects inherit directly from other objects, not from classes. Every object has a hidden link to another object called its prototype. When you access a property, JavaScript looks in the object first, then follows the prototype chain until found or reaching null.
How it works:
Each object has an internal prototype property accessible via underscore underscore proto underscore or Object.getPrototypeOf. Functions have a prototype property used when creating objects with new. New objects created from a constructor get that constructor's prototype as their prototype. Properties and methods can be shared through the prototype chain.
Classical inheritance:
Classes are blueprints for objects. Objects are instances of classes. Inheritance creates is-a relationships. Classes inherit from other classes using extends keyword.
Key differences:
JavaScript has no true classes, only objects. ES6 classes are syntactic sugar over prototypes. In classical OOP, you define classes then create instances. In prototypal OOP, you create objects that serve as prototypes for other objects. Prototypal inheritance is more flexible but can be confusing.
Advantages of prototypal inheritance:
More flexible and dynamic. Can change prototypes at runtime. Memory efficient by sharing methods. Simpler mental model, everything is an object.
Disadvantages:
Can be confusing for developers from classical OOP backgrounds. Easier to make mistakes with prototype chain. Less structure than class-based systems.
Best practices:
Use ES6 classes for cleaner syntax. Understand prototypes underneath. Share methods through prototype, not in constructor. Avoid modifying built-in prototypes.
Understanding prototypal inheritance is essential for mastering JavaScript and common in interviews.