如何在 Javascript 中的“window.location”上应用“get”代理?

Кон*_*Ван 4 javascript

我正在使用Chrome 60。我刚刚尝试在 上应用get 代理window.location

\n

它适用于前两个参考,但是,随后失败并出现Illegal invocation错误:

\n
location = new Proxy(location, {\n    get: (target, name) => {\n        console.log(name, target, "PROX");\n        return target[name];\n    }\n});\n
Run Code Online (Sandbox Code Playgroud)\n

错误消息是:

\n
\n

VM3495:3 符号(Symbol.toPrimitive) 位置 {\xe2\x80\xa6} "PROX"

\n

VM3495:3 toString 位置 {\xe2\x80\xa6} PROX

\n

未捕获的类型错误:非法调用:1:10

\n
\n
    \n
  1. 为什么它会抛出错误?
  2. \n
  3. 如何在 Javascript 中应用get代理window.location
  4. \n
\n

Ber*_*rgi 6

为什么它会抛出错误?

代理与SetssMap不兼容的原因相同:它们是本机对象,并且它们的方法(如toString的示例中所示)期望在具有相应内部插槽的本机对象上调用,而不是代理。

如何window.location在 Javascript 中应用 get Proxy on?

您需要将陷阱get拦截的所有方法绑定到目标:

new Proxy(location, {
    get: (target, name) => {
        console.log(name, target, "PROX");
        return typeof target[name] == "function"
          ? target[name].bind(target)
          : target[name];
    }
});
Run Code Online (Sandbox Code Playgroud)

然而,这仍然没有改变你不能用window.location你自己的实现替换全局。它是一个不可配置的属性,分配给它会导致导航不写入该属性。