为什么我的代理包装映射的函数调用会抛出类型错误?


var cache = new Proxy(new Map(), {
    apply: function(target, thisArg, argumentsList) {
        console.log('hello world!');
    }
});
cache.set('foo', 'bar');

据我所知,应该导致hello world!记录到控制台,并且未设置地图的foo密钥。但是,当我运行此功能时,它会抛出:

TypeError: Method Map.prototype.set called on incompatible receiver [object Object]
    at Proxy.set (native)
    at repl:1:7
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:340:29)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.onLine (repl.js:537:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:189:7)
    at REPLServer.Interface._onLine (readline.js:238:10)

我已经谷歌搜索了几次MDN代理文档,我无法缠绕我的头为什么不起作用。

有什么想法吗?我在node.js 7.5.0。

apply陷阱调用(如果您在函数代理),而不是方法调用(只是属性访问,调用和一些this Shenanigans)。您可以提供get并返回功能:

var cache = new Proxy(new Map(), {
    get(target, property, receiver) {
        return function () {
            console.log('hello world!');
        };
    }
});

我不认为您只是想覆盖Map的一部分吗?在这种情况下,您可以从其原型继承(如果是一个选项,这比代理人要好得多):

class Cache extends Map {
    set(key, value) {
        console.log('hello world!');
    }
}
const cache = new Cache();

相关内容

最新更新