首页 > 解决方案 > 为什么这个代理处理程序会导致无限递归?

问题描述

toString我使用 ES6 Proxy为该方法构建了一个钩子。在调试一些问题时,我注意到console.log处理程序无缘无故地被调用。

class Hook {
    constructor(object) {
        this.object = object;
    }

    toStringProperty() {
        const handler = {
            apply: (target, thisArg, args) => {

                console.log(target, thisArg, args);

                if (thisArg === Function.prototype.toString) {
                    return 'function toString() { [native code] }'
                }

                if (thisArg === this.object) {
                    return "Hooked String"
                }

                return target.apply(thisArg, args)
            }
        }

        Function.prototype.toString = new Proxy(Function.prototype.toString, handler)
    }
}

let hook = new Hook(HTMLAudioElement);
hook.toStringProperty()
HTMLAudioElement.toString();

我花了很多时间试图找出导致这种递归的原因,但我担心我找不到任何东西。

HTMLAudioElement注意:在输入或在控制台中也会发生此行为ooo,当然您必须在运行上述代码后执行此操作。我的浏览器是 Chrome。我使用 Devtools 控制台进行了测试。

标签: javascriptrecursiones6-proxy

解决方案


在处理程序内部,您调用console.log(target, thisArg, args);wheretargetthisArgare 函数。devtools 控制台似乎用于.toString()获取要显示它的函数的名称。


推荐阅读