Prototype Inheritance vs Classical Inheritance
JavaScript uses prototypal inheritance, which is fundamentally different from classical inheritance found in languages like Java or C++. Understanding this difference is crucial for JavaScript developers.
Prototypal Inheritance
// Prototypal Inheritance Example
const animal = {
makeSound() {
console.log(this.sound);
}
};
const dog = Object.create(animal);
dog.sound = "Woof!";
dog.makeSound(); // Outputs: Woof!Constructor Functions
// Constructor Function Pattern
function Animal(name) {
this.name = name;
}
Animal.prototype.makeSound = function() {
console.log(this.sound);
};
function Dog(name) {
Animal.call(this, name);
this.sound = "Woof!";
}
// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const rex = new Dog("Rex");
rex.makeSound(); // Outputs: Woof!Key Differences from Classical Inheritance
- JavaScript uses prototype chain instead of class inheritance
- Objects inherit directly from other objects
- More flexible than classical inheritance
- Can change behavior at runtime
ES6 Class Syntax
// Modern Class Syntax (Still uses prototypes under the hood)
class Animal {
constructor(name) {
this.name = name;
}
makeSound() {
console.log(this.sound);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
this.sound = "Woof!";
}
}
const rex = new Dog("Rex");
rex.makeSound(); // Outputs: Woof!Common Interview Follow-up Questions
- How does the prototype chain work in JavaScript?
- What are the advantages of prototypal inheritance over classical inheritance?
- How does the 'new' keyword work internally?
- What is the difference between Object.create() and the constructor pattern?
Best Practices
- Prefer composition over inheritance
- Use ES6 class syntax for clearer code structure
- Be careful with prototype manipulation in production code
- Understand that classes are just syntax sugar over prototypes