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

226
Views
Increment an object count variable by one, every time one of the many object methods is invoked/called

Let's say we have the following object:

class Foo{
     constructor(){
          this.count = 0;
     }
     method1() { <does something> }
     method2() { <does something else> }
     method3() { <does something even more> }
}

Now obviously we can add the following line of code to EACH method and the count will update:

this.count++;

While I know it's only one line code one can say that it is a redundant line of code. So is there way that we can detect if an object method has been invoked, no matter which one it is, and then update the count?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You might iterate over a separate object of methods to add instead, and have them do this.count++ first.

class Foo{
     constructor(){
          this.count = 0;
     }
}
const methods = {
  method1() {
    console.log('m1');
  },
  method2() {
    console.log('m2');
  },
  method3() {
    console.log('m3');
  },
};
for (const [key, value] of Object.entries(methods)) {
  Foo.prototype[key] = function(...args) {
    this.count++;
    value(...args);
  }
}

const f = new Foo();
f.method1();
f.method1();
f.method2();
console.log(f.count);

about 4 years ago · Juan Pablo Isaza 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!