0
0
Javascriptprogramming~15 mins

Inheritance using classes in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - Inheritance using classes
What is it?
Inheritance using classes is a way to create a new class based on an existing class. The new class, called a child or subclass, gets all the features of the original class, called the parent or superclass. This lets you reuse code and add new features without rewriting everything. It works like a family tree where children inherit traits from their parents.
Why it matters
Inheritance helps programmers avoid repeating code by sharing common features between classes. Without inheritance, every new class would need to be built from scratch, making programs longer and harder to fix. It also helps organize code in a clear way, making it easier to understand and update. This saves time and reduces mistakes in real projects.
Where it fits
Before learning inheritance, you should understand basic classes and objects in JavaScript. After mastering inheritance, you can learn about advanced topics like polymorphism, method overriding, and design patterns that use inheritance.
Mental Model
Core Idea
Inheritance lets a new class copy and extend the features of an existing class, like children inheriting traits from their parents.
Think of it like...
Inheritance is like a family recipe passed down from parents to children, where the children can use the original recipe and add their own twist.
Parent Class
  ┌─────────────┐
  │  Animal     │
  │  - breathe  │
  │  - eat      │
  └─────┬───────┘
        │ inherits
        ▼
Child Class
  ┌─────────────┐
  │  Dog        │
  │  - bark     │
  │  - fetch    │
  └─────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Basic Classes
🤔
Concept: Learn what classes are and how to create objects from them.
In JavaScript, a class is like a blueprint for creating objects. You define properties and methods inside a class. For example: class Animal { constructor(name) { this.name = name; } speak() { return `${this.name} makes a sound.`; } } const animal = new Animal('Generic'); console.log(animal.speak());
Result
Output: 'Generic makes a sound.'
Understanding classes as blueprints is key before adding inheritance, because inheritance builds on this idea.
2
FoundationCreating Objects from Classes
🤔
Concept: Learn how to make instances (objects) from classes and use their methods.
You create an object by using the 'new' keyword with a class. This object has its own properties and can use the class methods. const dog = new Animal('Doggy'); console.log(dog.speak());
Result
Output: 'Doggy makes a sound.'
Knowing how to create and use objects helps you see what inheritance will extend or change.
3
IntermediateIntroducing Inheritance with extends
🤔Before reading on: Do you think a child class can use methods from its parent class without rewriting them? Commit to your answer.
Concept: Learn how to create a child class that inherits from a parent class using the 'extends' keyword.
You can make a new class inherit from an existing one by using 'extends'. The child class gets all the parent's methods automatically. class Dog extends Animal { bark() { return `${this.name} barks.`; } } const dog = new Dog('Buddy'); console.log(dog.speak()); console.log(dog.bark());
Result
Output: 'Buddy makes a sound.' 'Buddy barks.'
Understanding that inheritance copies methods lets you reuse code and add new features easily.
4
IntermediateUsing super to Call Parent Constructor
🤔Before reading on: Do you think the child class constructor automatically runs the parent constructor? Commit to your answer.
Concept: Learn how to call the parent class constructor inside the child class using 'super()'.
When a child class has its own constructor, it must call 'super()' to run the parent's constructor and set up inherited properties. class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } bark() { return `${this.name} barks.`; } } const dog = new Dog('Buddy', 'Beagle'); console.log(dog.name); console.log(dog.breed);
Result
Output: 'Buddy' 'Beagle'
Knowing to call 'super()' prevents errors and ensures the parent class sets up its part of the object.
5
IntermediateOverriding Parent Methods
🤔Before reading on: If a child class defines a method with the same name as the parent, which one runs? Commit to your answer.
Concept: Learn how child classes can replace parent methods by defining methods with the same name.
A child class can change how a method works by writing its own version. This is called overriding. class Dog extends Animal { speak() { return `${this.name} barks loudly.`; } } const dog = new Dog('Buddy'); console.log(dog.speak());
Result
Output: 'Buddy barks loudly.'
Understanding overriding lets you customize inherited behavior without changing the parent class.
6
AdvancedCalling Parent Methods with super.method()
🤔Before reading on: Can a child method call the parent's version of the same method? Commit to your answer.
Concept: Learn how to call the parent class's method from inside an overridden method using 'super.method()'.
Inside an overridden method, you can use 'super.methodName()' to run the parent's method and add extra behavior. class Dog extends Animal { speak() { return super.speak() + ` And ${this.name} barks.`; } } const dog = new Dog('Buddy'); console.log(dog.speak());
Result
Output: 'Buddy makes a sound. And Buddy barks.'
Knowing how to combine parent and child methods helps build flexible and maintainable code.
7
ExpertPrototype Chain and Inheritance Internals
🤔Before reading on: Do you think inheritance copies methods into the child class or links to them? Commit to your answer.
Concept: Understand how JavaScript uses the prototype chain to link child classes to parent classes without copying methods.
JavaScript does not copy methods from parent to child. Instead, it links the child class's prototype to the parent's prototype. When a method is called, JavaScript looks up the chain until it finds it. This means changes to the parent's prototype affect all children. Example: Dog.prototype.__proto__ === Animal.prototype // true This is why inheritance is fast and memory efficient.
Result
Output: true
Understanding the prototype chain reveals why inheritance is dynamic and how method lookups work behind the scenes.
Under the Hood
JavaScript classes are syntactic sugar over prototype-based inheritance. When you create a class that extends another, the child class's prototype object is linked to the parent's prototype. This link forms the prototype chain. When you call a method on an object, JavaScript first looks for it on the object itself, then on its prototype, then up the chain until it finds the method or reaches the end. The 'super' keyword allows child classes to access parent methods and constructors by referencing this chain.
Why designed this way?
JavaScript was designed with prototype-based inheritance to be flexible and dynamic. Classes were added later to make this easier to understand and write. Linking prototypes instead of copying methods saves memory and allows changes to parent methods to reflect immediately in children. This design balances performance with ease of use and supports powerful patterns like method overriding and dynamic dispatch.
Object Instance
  ┌───────────────┐
  │ dog (object)  │
  └──────┬────────┘
         │ __proto__
         ▼
Dog.prototype (child class methods)
  ┌───────────────┐
  │ bark(), speak()│
  └──────┬────────┘
         │ __proto__
         ▼
Animal.prototype (parent class methods)
  ┌───────────────┐
  │ speak(), eat() │
  └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does inheritance copy all parent methods into the child class? Commit to yes or no.
Common Belief:Inheritance copies all methods from the parent class into the child class's code.
Tap to reveal reality
Reality:Inheritance links the child class's prototype to the parent's prototype; methods are not copied but looked up dynamically.
Why it matters:Believing methods are copied can lead to confusion about why changes to parent methods affect children and why memory usage is efficient.
Quick: If a child class has no constructor, does the parent constructor run automatically? Commit to yes or no.
Common Belief:The parent constructor always runs automatically, even if the child class has its own constructor.
Tap to reveal reality
Reality:If the child class defines a constructor, it must explicitly call 'super()' to run the parent constructor; otherwise, an error occurs.
Why it matters:Not calling 'super()' causes runtime errors and breaks object initialization, confusing beginners.
Quick: Does overriding a method in a child class delete the parent's method? Commit to yes or no.
Common Belief:Overriding a method in the child class removes the parent's version completely.
Tap to reveal reality
Reality:The parent's method still exists and can be accessed using 'super.method()' inside the child method.
Why it matters:Misunderstanding this limits the ability to extend behavior and reuse parent logic safely.
Quick: Can you inherit from multiple classes in JavaScript using 'extends'? Commit to yes or no.
Common Belief:JavaScript allows a class to extend multiple parent classes at once.
Tap to reveal reality
Reality:JavaScript classes can only extend one parent class; multiple inheritance is not supported directly.
Why it matters:Expecting multiple inheritance can lead to design mistakes; alternatives like mixins or composition should be used.
Expert Zone
1
The 'super' keyword behaves differently in static methods versus instance methods, requiring careful use in advanced class hierarchies.
2
Modifying a parent's prototype after child classes are created affects all children immediately, which can be powerful but risky in large codebases.
3
JavaScript's single inheritance model encourages composition and mixins for code reuse, which experts use to avoid deep inheritance chains.
When NOT to use
Inheritance is not ideal when classes need to share behavior from multiple sources; in such cases, composition or mixins are better. Also, deep inheritance hierarchies can make code hard to understand and maintain, so prefer flat structures or interfaces when possible.
Production Patterns
In real-world JavaScript, inheritance is often used to create base classes for UI components or data models, with child classes adding specific features. Frameworks like React use composition more than inheritance, but inheritance remains useful for shared logic and utility classes.
Connections
Polymorphism
Inheritance enables polymorphism by allowing child classes to override parent methods.
Understanding inheritance helps grasp how different objects can be treated the same way but behave differently.
Object Composition
Composition is an alternative to inheritance for sharing behavior by combining objects.
Knowing inheritance's limits clarifies when to use composition for more flexible and maintainable code.
Biological Genetics
Inheritance in programming mirrors genetic inheritance where offspring inherit traits from parents.
Seeing inheritance as a natural process helps understand why traits (methods) can be shared and modified across generations (classes).
Common Pitfalls
#1Forgetting to call super() in child constructor
Wrong approach:class Dog extends Animal { constructor(name) { this.name = name; // Error: 'this' used before super() } }
Correct approach:class Dog extends Animal { constructor(name) { super(name); this.name = name; } }
Root cause:Beginners often don't know that 'super()' must be called before using 'this' in child constructors.
#2Overriding methods without calling parent method when needed
Wrong approach:class Dog extends Animal { speak() { return `${this.name} barks.`; } }
Correct approach:class Dog extends Animal { speak() { return super.speak() + ` And ${this.name} barks.`; } }
Root cause:Not realizing that sometimes you want to keep parent behavior and add to it, not replace it entirely.
#3Trying to extend multiple classes directly
Wrong approach:class Dog extends Animal, Pet { // Syntax error }
Correct approach:// Use composition or mixins instead function mixin(target, ...sources) { Object.assign(target.prototype, ...sources); } class Dog extends Animal {} mixin(Dog, Pet);
Root cause:Misunderstanding JavaScript's single inheritance model and expecting multiple inheritance like other languages.
Key Takeaways
Inheritance allows a child class to reuse and extend the features of a parent class, saving time and effort.
The 'extends' keyword creates a link between child and parent classes, forming a prototype chain for method lookup.
Calling 'super()' in child constructors is essential to properly initialize inherited properties.
Overriding methods lets child classes customize behavior, and 'super.method()' allows combining parent and child logic.
JavaScript inheritance is prototype-based, meaning methods are shared via links, not copies, making it efficient and dynamic.