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

前端 未结 1 525
挽巷
挽巷 2020-12-21 15:18
var cache = new Proxy(new Map(), {
    apply: function(target, thisArg, argumentsList) {
        console.log(\'hello world!\');
    }
});

cache.set(\'foo\', \'bar\'         


        
相关标签:
1条回答
  • 2020-12-21 15:32

    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();
    
    0 讨论(0)
提交回复
热议问题