JavaScript Class extends Keyword

Definition and Usage

extends Keywords are used to create a subclass (parent) of another class.

The subclass inherits all methods of another class.

Inheritance is very useful for code reusability: when creating a new class, reuse the properties and methods of existing classes.

Note:From the above example, we can see that,super() Method refers to the parent class. By calling super() Methods, we will call the parent class's constructor and can access the parent class's properties and methods.

Instance

Create a class named "Model" that will inherit the methods of the "Car" class:

class Car {
  constructor(brand) {
    this.carname = brand;
  }
  present() {
    return 'I have a ' + this.carname;
  }
}
class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return this.present() + ', it is a ' + this.model;
  }
}
mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();

Try It Yourself

Syntax

class childClass extends parentClass

Technical Details

JavaScript Version: ECMAScript 2015 (ES6)

Browser Support

Keywords Chrome IE Firefox Safari Opera
extends 49.0 13.0 45.0 9.0 36.0

Related Pages

JavaScript Tutorial:JavaScript Class

JavaScript Tutorial:JavaScript ES6 (EcmaScript 2015)

JavaScript Reference Manual:super Keyword

JavaScript Reference Manual:constructor() Method