Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

282
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda