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

156
Vistas
In a javascript Class declaration, which is the diference between declaring a method inside the constructor and the body?

I need some light here please! I understand that everything that is inside the constructor function its called with the new keyword and initialized. so as shown in the snippet, below when I log the mycar instance, i can see the method declared inside the constructor but not the one declared in the body.

so the question are: 1)why im able to call succesfully the method defined in the body if is not among the propertys of the instance? 2) why at all I declare the methods in the body and not just inside the constructor? in the snipet below both are working

class car {
  constructor(_brand, _year, _color) {
    this.brand = _brand;
    this.year = _year;
    this.color = _color;
    // a method defined inside the constructor--------------------------
    this.get_brand_color = function () {
      return this.brand + this.color;
    };
  }
   // a method defined in the body of the class-----------------------------
  get_brand_year() {
    return this.brand + this.year;
  }
}

mycar = new car("chevrolet ", 1997, "red");

console.log(mycar); 
// logs: car {brand: 'chevrolet ', year: 1997, color: 'red', get_brand_color: ƒ}
console.log(mycar.get_brand_year());
// logs:chevrolet 1997
console.log(mycar.get_brand_color());
// logs:chevrolet red

about 4 years ago · Juan Pablo Isaza
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