Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda