0
0
JavascriptHow-ToBeginner · 4 min read

How to Use Inheritance in JavaScript: Simple Guide

In JavaScript, inheritance lets one class or object get properties and methods from another using extends keyword for classes or Object.create() for objects. This helps reuse code and create a clear relationship between parent and child objects.
📐

Syntax

JavaScript uses the class syntax with extends to create inheritance between classes. The super() function calls the parent class constructor.

  • class Child extends Parent: Child inherits from Parent.
  • constructor(): Initializes the child object.
  • super(): Calls the parent constructor.
javascript
class Parent {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name); // call Parent constructor
    this.age = age;
  }
  showAge() {
    return `I am ${this.age} years old.`;
  }
}
💻

Example

This example shows a Parent class and a Child class that inherits from it. The child can use parent's methods and add its own.

javascript
class Parent {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, my name is ${this.name}`;
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
  showAge() {
    return `I am ${this.age} years old.`;
  }
}

const child = new Child('Alice', 10);
console.log(child.greet());
console.log(child.showAge());
Output
Hello, my name is Alice I am 10 years old.
⚠️

Common Pitfalls

Common mistakes include forgetting to call super() in the child constructor, which causes errors, or trying to inherit from non-class objects incorrectly. Also, overriding methods without calling super.method() can lose parent behavior.

javascript
class Parent {
  greet() {
    return 'Hello from Parent';
  }
}

// Wrong: Missing super() in constructor
class ChildWrong extends Parent {
  constructor() {
    super(); // Added super() to fix error
  }
}

// Right: Call super() in constructor
class ChildRight extends Parent {
  constructor() {
    super();
  }
  greet() {
    return super.greet() + ' and Child';
  }
}
📊

Quick Reference

  • extends: Use to inherit from a parent class.
  • super(): Call parent constructor inside child constructor.
  • super.method(): Call parent method inside overridden child method.
  • Object.create(proto): Alternative way to inherit from an object.

Key Takeaways

Use extends to create a child class that inherits from a parent class.
Always call super() in the child constructor before using this.
Child classes can override parent methods and call them with super.method().
Inheritance helps reuse code and organize related objects clearly.
For object inheritance, Object.create() can be used as an alternative.