gpt4 book ai didi

javascript - 有没有办法在javascript中代理(拦截)一个类的所有方法?

转载 作者:行者123 更新时间:2023-12-05 01:56:26 34 4
gpt4 key购买 nike

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

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 循环是一种有趣的方法,但那时我可以只在每个函数的第一行中实现逻辑。

最佳答案

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

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

关于javascript - 有没有办法在javascript中代理(拦截)一个类的所有方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69860820/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com