Search code examples
javascriptes6-proxy

Why are proxy traps not invoked for instances constructed from a proxied constructor?


I'm trying to register function change via proxies with this code:

const handler = {
  construct(objTarget, args, oldConstructor) {
     return new objTarget(...args)
  },
  set(target, key, value) {
    console.log(`Setting value ${key} as ${value}`)
    target[key] = value;
  },
  get(target, key) {
    console.log(`Reading value from ${key}`)
    return target[key];
  },
};

function wand (args){console.log(args)}

const Wand = new Proxy(wand, handler);

var w = new Wand(["some","args"]);

When I type

Wand.a = 10

I get output

>Setting value a as 10

But if i type

w.a = 10

Handler "get" outputs nothing

How do i get code working for "w.a = 10"? This is part of codewars.com challenge, so

var w = new Wand(["some","args"]); 

is predefined and I can't modify it.

PS: Please, don't spoil how to accomplish this challenge, I'd like to know only how to get this part done. Or suggest another way how to get this done.

Thank you!


Solution

  • Notice the handler.construct() is simply

    return new objTarget(...args)
    

    There's nothing special about the returned value, it's just an instance of the proxy's target wand so something like

    return new Proxy(new objTarget(...args), someHandler)
    

    would allow you to intercept operations on w based on the traps defined in someHandler.