有没有一种方法可以代理(拦截)JavaScript中类的所有方法?

vc9ivgsu  于 5个月前  发布在  Java
关注(0)|答案(2)|浏览(61)

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

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

tnkciper

tnkciper1#

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

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

字符串

jdgnovmf

jdgnovmf2#

他们在代理上添加了apply方法,这些代理将捕获方法调用。enter link description here

function sum(a, b) {
    return a + b;
}

const handler = {
    apply: function (target, thisArg, argumentsList) 
    {
        console.log(`Calculate sum: ${argumentsList}`);
        // Expected output: "Calculate sum: 1,2"

        return target(argumentsList[0], argumentsList[1]) * 10;
    },
};

const proxy1 = new Proxy(sum, handler);

console.log(sum(1, 2));
// Expected output: 3
console.log(proxy1(1, 2));
// Expected output: 30

字符串

相关问题