Home > Net >  Increment an object count variable by one, every time one of the many object methods is invoked/call
Increment an object count variable by one, every time one of the many object methods is invoked/call

Time:09-17

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?

CodePudding user response:

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

  • Related