Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

97
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!