为什么我的代理包装Map的函数调用抛出TypeError? [英] Why is my Proxy wrapping a Map's function calls throwing TypeError?

查看:657
本文介绍了为什么我的代理包装Map的函数调用抛出TypeError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

cache.set('foo', 'bar');

据我所知,这个应该结果 hello world!正在登录到控制台,并且地图的 foo 键未设置。但是,当我运行它时,它会抛出:

As far as I can tell this should result in hello world! being logged to the console and the Map's foo key not being set. However, when I run this, it throws:

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)

我已经Googled并将所有的MDN代理文档多次,我不能包围我为什么这不工作。

I've Googled and gone over all the MDN Proxy docs several times, and I can't wrap my head around why this isn't working.

任何想法?我在Node.js 7.5.0上。

Any ideas? I'm on Node.js 7.5.0.

推荐答案

apply 陷阱调用(如果你正在代理一个函数),而不是方法调用(只是属性访问,一个调用,一些这个 shenanigans)。您可以提供 get 并返回一个函数:

apply traps calling (if you were proxying a function), not method calls (which are just property access, a call, and some this shenanigans). You could supply get and return a function instead:

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

我不认为你只是想覆盖地图的部分,但是在这种情况下,您可以继承其原型(这是一个比代理更好的选择,如果它是一个选项):

I don’t suppose you’re just trying to override parts of Map, though? You can inherit from its prototype in that case (this is a much better option than the proxy if it’s an option at all):

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

const cache = new Cache();

这篇关于为什么我的代理包装Map的函数调用抛出TypeError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆