Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Difference between super and this while calling a function in sub class in js

class A {
  data1 = 1;
  constructor(){
    this.data2 = 2;
  }
  test() { console.log(this) }
}
class B extends A {
  constructor() {
    super();
  }
  funcA() { this.test() }
  funcB() { super.test() }
}
let foo = new B()
foo.funcA();
foo.funcB();

what's the difference between funcA() and funcB() while calling, or they are exactly the same thing? BTW, what's the difference between data1 and data2 declared in and out the constructor, which is preferred

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

With this.test(), you reference the instance. No test property exists directly on the instance, so as with standard prototypal inheritance, the prototype object is examined for the property. This prototype is A.prototype, which does have a test property, so that gets called.

With super.test(), you instead start looking for the test property on the superclass - A.prototype, which is found immediately and called.

If you had a test method on B as well, you'd see the difference.

class A {
  data1 = 1;
  constructor(){
    this.data2 = 2;
  }
  test() { console.log('a') }
}
class B extends A {
  constructor() {
    super();
  }
  test() {
    console.log('b');
  }
  funcA() { this.test() }
  funcB() { super.test() }
}
const foo = new B()
foo.funcA();
foo.funcB();

BTW, what's the difference between data1 and data2 declared in and out the constructor, which is preferred

It's up to you. Though, class fields (assigning outside of the constructor) are slightly more concise (especially if your constructor doesn't contain anything else) but less supported - if you want to use them, make sure to transpile your code.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda