JavaScript Inheritance

A class can extendanother class, and objects initialized using that class inherit all the methods of both classes.

Suppose we have a class Person:


class Person {
  hello(){  
    return "Hello, I am Person";
  }
};
            

We can define a new class Programmerthat extends Person:


class Programmer  extends Person {}
            

Now if we instantiate a new object with class Programmer, it has access to the hello()method:


const codingkoleji = new Programmer();
codingkoleji.hello(); //'Hello, I am a Person'
            

Example


class Person {
  hello(){  
    return "Hello, I am Person";
  }
};

class Programmer  extends Person {}

const codingkoleji = new Programmer();

console.log(codingkoleji.hello()); //'Hello, I am a Person'
  

Inside a child class, you can reference the parent class calling super():


class Programmer extends Person{
  hello(){  
    return super.hello() + `. I am a programmer.`; // Call the parent class method
  }
};

const programmer = new Programmer();
programmer.hello(); //'Hello, I am a Person. I am also a programmer.'
            

The above program prints Hello, I am a Person. I am also a programmer..

Example


class Person {
  constructor(user){
    this.user = user;
  }
  hello(){  
    return `Hello, my name is ${this.user}`;
  }
}

class Programmer extends Person{
  constructor(user, language){
    super(user); // Call the parent class constructor
    this.language = language;
  }

  hello(){  
    return super.hello() + `. I am a programmer and I love ${this.language}.`; // Call the parent class method
  }
}

const programmer = new Programmer('Alice', 'JavaScript');

console.log(programmer.hello()); // Output: Hello, my name is Alice. I am a programmer and I love JavaScript.

super() keyword is used to call functions on an object's parent class. It can be used in two primary contexts:

  • Inside a constructor: super()is used to call the constructor of the parent class. This is necessary when you need to initialize properties inherited from the parent class.
  • Inside a method: super.methodName()is used to call a method defined in the parent class from within a method of a child class.