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

256
Vistas
Getters vs functions for internal properties

Consider this code snippet

class A {
  constructor() {
   this._val = 5;
  }
  
  get val() {
    return this._val;
  }
  
  getVal() {
    return this._val;
  }
}

const a = new A();
console.log(`A.val: ${a.val}, A.getVal: ${a.getVal()}`);
  

Obtaining _val of object a works via both the accessor get val() as well as the regular method getVal(). Are there any differences between the two other than that the former exposes a property val on a whereas getVal() is function that is exposed as a property on a? Would there be any performance/ coding guideline considerations on when to adopt one over the other?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Take a look at the difference:

class A {
  constructor() {
   this._val = 5;
  }
  
  get val() {
    return this._val;
  }
  
  getVal() {
    return this._val;
  }
}

const a = new A();
console.log(a);
console.log(`A.val: ${a.val}, A.getVal: ${a.getVal()}`);

class B {
  constructor() {
   this._val = 6;
  }
  
  getVal() {
    return this._val;
  }
}

const b = new B();
console.log(b);
console.log(`B.val: ${b.val}, B.getVal: ${b.getVal()}`);
  

You'll notice that get exposes _val directly as a property. The function is a function that accesses _val. That's really the only difference. Use get if you just want the property to be accessible. Use the function is you want to do stuff the variable before making it accessible, like, formatting a date, for example.

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