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

241
Visualizações
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 Respostas
Responde à pergunta

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