Why is Proxy to a Map object in ES2015 not working Why is Proxy to a Map object in ES2015 not working google-chrome google-chrome

Why is Proxy to a Map object in ES2015 not working


The reason you're getting the error is that the proxy isn't getting involved in the p1.set call (other than that the set trap — unrelated, despite same name — is getting called to retrieve the function reference). So once the function reference has been retrieved, it's called with this set to the proxy, not the Map — which Map doesn't like.

If you're really trying to intercept all property access calls on the Map, you can fix it by binding any function references you're returning from get (see the *** lines):

const loggingProxyHandler = {    get(target, name/*, receiver*/) {        let ret = Reflect.get(target, name);        console.log(`get(${name}=${ret})`);        if (typeof ret === "function") {    // ***          ret = ret.bind(target);           // ***        }                                   // ***        return ret;     },     set(target, name, value/*, receiver*/) {         console.log(`set(${name}=${value})`);         return Reflect.set(target, name, value);     }};function onRunTest() {    const m1 = new Map();    const p1 = new Proxy(m1, loggingProxyHandler);    p1.set("a", "aval");    console.log(p1.get("a")); // "aval"    console.log(p1.size);     // 1}onRunTest();
NOTE: Requires a browser supporting ES2015's Proxy