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

96
Visualizações
How to define a property function on getter property?

Is there a way to add a property on a getter function?

Ideally, the code I want to write is:

const obj = {
  log: ['a', 'b', 'c'],
  get latest() {
    return this.log[this.log.length - 1];
  }
};

obj.latest.test = () => 123;

console.log(obj.latest);
// expected output: "c"
console.log(obj.latest.test())
// expect output: 123

My actual desire is this: since my getter perform a pretty huge computation, for instance:

const obj = {
  otherproperties: ['a', 'b', 'c'],
  get items() {
    // VERY HUGE COMPUTATION...
    return [item0, item1, item2, item3]
  }
};

and sometimes I need only an element from the result, I want to write something:

obj.items.withId = (id) => {
  // Don't run the entire huge computation but..
  return computeOnlyId(id);
}

so to be able to write obj.items if I want all the values, or obk.items.withId(1) if I want only a specific item.

Probably, editing this question, I already understood that this is impossible since items it's a getter but I leave to you the keyboards for the answers.

What I would like to avoid is to have to write obj.items.all() to get all of them and obj.items.withId(id) to get only once.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

obj.latest is going to be the result of this.log[this.log.length - 1] which is going to be 'c'.

Since 'c' is a primitive, you can't (usefully) assign properties to it.

about 4 years ago · Santiago Gelvez 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