Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

javascript - Why is my Proxy wrapping a Map's function calls throwing TypeError?

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

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

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)

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...