Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

super

Esta tradução está incompleta. Ajude atraduzir este artigo.

A palavra-chave super é usada para acessar o objeto parente de um objeto, em outros casos, é usada para acessar a classe parente de uma classe.

Síntaxe

// chama o objeto (ou construtor) parente
super(...[arguments]);
// chama um método da classe/objeto parente
super.método([arguments]);

Descrição

Quando usada no construtor de uma classe, a palavra-chave super deveria ser usada apenas uma vez, e precisa ser usada antes que a palavra-chave this possa ser usada. Essa palavra-chave também pode ser usada para chamar uma função ou objeto pai.

Exemplo

Usando super em classes

Esse trexo de código foi obtido através de classes sample (demonstração).

class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
}

class Square extends Polygon {
  constructor(length) {
    this.height; // ReferenceError, precisa chamar o super primeiro!
    
    // Aqui, ele chama a classe construtora pai com o tamanho 
    // provido pelo Polygon -> width e height
    super(length, length);
    
    // Note: 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;
  } 
}

Super-calling static methods

You are also able to call super on static methods.

class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong';
  }
}
Computer.pingpong(); // 'ping pong'

Deleting super properties will throw

You can not use the delete operator and super.prop or super[expr] to delete a parent class' property, it will throw a ReferenceError.

class Base {
  constructor() {}
  foo() {}
}
class Derived extends Base {
  constructor() {}
  delete() {
    delete super.foo;
  }
}

new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 

Super.prop can not overwrite non-writable properties

When defining non-writable properties with e.g. Object.defineProperty, super can not overwrite the value of the property.

class X {
  constructor() {
    Object.defineProperty(this, "prop", {
      configurable: true,
      writable: false, 
      value: 1
    });
  } 
  f() { 
    super.prop = 2;
  }
}

var x = new X();
x.f();
console.log(x.prop); // 1

Using super.prop in object literals

Super can also be used in the object initializer / literal notation. In this example, two objects define a method. In the second object, super calls the first object's method. This works with the help of Object.setPrototypeOf() with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1.

var obj1 = {
  method1() {
    console.log("method 1");
  }
}

var obj2 = {
  method2() {
   super.method1();
  }
}

Object.setPrototypeOf(obj2, obj1);
obj2.method2(); // logs "method 1"

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'super' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'super' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 42.0 45 (45) ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? 42.0 45.0 (45) ? ? ? 42.0

Gecko specific notes

  • super() does not yet work as expected for built-in prototypes.

See also

Etiquetas do documento e colaboradores

 Colaboradores desta página: nicematt, iFgR
 Última atualização por: nicematt,