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

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

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