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

273
Visualizações
Is there a way to proxy (intercept) all methods of a class in javascript?

I want to be able to proxy all methods of a class inside the constructor of a class itself.

class Boy {
    constructor() {
        // proxy logic, do something before each call of all methods inside class
        // like if arg passed is 3, print something additionally
    }

    run(meters) {
        console.log(meters)
    }

    walk(meters) {
        // walk
    }
}

const myBoy = new Boy();
console.log(myBoy.run(3)) // should print 3 and something else

I think a for loop for each method would be an interesting approach, but at that point I could just implement the logic in the first lines of each function.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I realized I could just create a proxy with the target as the class object itself and then index the method.

class Boy {
    constructor() {
        // proxy logic, do something before each call of all methods inside class
        // like if arg passed is 3, print something additionally
        return new Proxy(this, {
            get(target, prop) {
                const origMethod = target[prop];
                if (typeof origMethod == 'function') {
                    return function (...args) {
                        if (args[0] == 3) {
                            return "3 is unlucky, you didn't go anywhere."
                        }
                        let result = origMethod.apply(target, args)
                        return result
                    }
                }
            }
        })
    }

    run(meters) {
        return `you ran ${meters}!`
    }

    walk(meters) {
        return `you walked ${meters}!`
        // walk
    }
}

const myBoy = new Boy();
console.log(myBoy.run(2)) // prints "you ran 2!"
console.log(myBoy.walk(3)) // prints "3 is unlucky, you didn't run."
console.log(myBoy.run(3)) // prints "3 is unlucky, you didn't run."
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