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

260
Visualizações
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 Respostas
Responde à pergunta

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 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