【问题标题】:Is there a way to proxy (intercept) all methods of a class in javascript?有没有办法在javascript中代理(拦截)类的所有方法?
【发布时间】:2021-12-19 22:56:30
【问题描述】:

我希望能够在类本身的构造函数中代理类的所有方法。

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

我认为每个方法的 for 循环会是一种有趣的方法,但那时我可以在每个函数的第一行中实现逻辑。

【问题讨论】:

  • 您还希望记录什么?
  • 不清楚你想要实现什么
  • 一秒更新代码,让代码更清晰
  • 您不想使用代理。这听起来更像是你想要装饰器。你不妨把它们放在类上,而不是放在构造函数中——除非每个实例都需要自己的特殊拦截?
  • “应该打印 3 和其他内容” - 还有什么其他内容?如果你“只在每个函数的第一行实现逻辑”,你的类会是什么样子?无论如何,您可能应该先这样做。

标签: javascript class oop ecmascript-6 es6-class


【解决方案1】:

我意识到我可以创建一个代理,将目标作为类对象本身,然后索引该方法。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多