extends

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

A palavra chave extends é usada em uma class declarations ou class expressions para criar uma classe filha de outra classe.

Sintaxe

class ChildClass extends ParentClass { ... }

Descrição

A palavra chave extends pode ser usada para tanto classes filhas quanto objetos filhos pré-construidos.

O .prototype da extensão deve ser um Object ou null.

Exemplos

Usando extends

O primeiro exemplo cria uma classe chamada Square a partir de uma classe chamada Polygon. Este exemplo foi extraido deste live demo (source).

js
class Square extends Polygon {
  constructor(length) {
    // Here, it calls the parent class' constructor with lengths
    // provided for the Polygon's width and height
    super(length, length);
    // Nota: In derived classes, super() must be called before you
    // can use 'this'. Leaving this out will cause a reference error.
    this.name = "Square";
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}

Usando extends com objetos pré-construidos

Este exemplo extende o objeto pré-construido Date. Este exemplo foi extraido deste live demo (source).

js
class myDate extends Date {
  constructor() {
    super();
  }

  getFormattedDate() {
    var months = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ];
    return (
      this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear()
    );
  }
}

Estendendo null

Estender de null funciona como em uma classe normal, exceto que o objeto prototype não herda de Object.prototype (en-US).

js
class nullExtends extends null {
  constructor() {}
}

Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype); // null

Especificações

Specification
ECMAScript Language Specification
# sec-class-definitions

Compatibilidade com navegadores

BCD tables only load in the browser

Ver também