Skip to content Skip to sidebar Skip to footer

Javascript: Why Doesn't Proxy Intercept Methods

I can't figure out why the apply trap isn't being called here: The output is: p1 descriptors: length,name,prototype,now,parse,UTC p1.now(): 1628887199300 p2.getFullYear(): 2021 S

Solution 1:

The apply trap only handles direct calls to a function. If you want to intercept invocations of the new operator, you need to use the construct trap:

let p1 = new Proxy(Date, {
  apply: function(target, that, args) {
      console.log(`function called ${target.name}`);
      return target.apply(args);
  },
  construct: function(target, that, args) {
    console.log(`function constructed ${target.name}`);
    return Reflect.construct(...arguments)
  }
});
console.log(`p1 descriptors: ${Object.getOwnPropertyNames(p1)}`);

console.log(`p1.now(): ${p1.now()}`)
let p2 = new p1();
console.log(`p2.getFullYear(): ${p2.getFullYear()}`)

Solution 2:

I was able to find the answer thanks to @VLAZ, but I wanted to post the completed answer here as the original question was trying to get the apply method to work. I also followed the example in @Bergi's comment which used bind to fix the problem w/ date and allowed me to reuse the function definition for the get trap:

let get = function(getTarget, p) {
  console.log(`get called: ${getTarget.name || p}`);
  return new Proxy(getTarget[p], {
    apply: function(applyTarget, that, args) {
      console.log(`function called: ${applyTarget.name}`);
      return Reflect.apply(applyTarget, getTarget, args);
    }
  });
}


let handler = {
  construct: function(t1, argArray) {
    console.log(`ctor called ${t1.name}`);
    let result = Reflect.construct(t1, argArray);
    let p = new Proxy(result, {
      get: get,
    });
    return p;
  },
  get: get
};

let p1 = new Proxy(Date, handler);
console.log(`p1 descriptors: ${Object.getOwnPropertyNames(p1)}`);
console.log(`p1.now(): ${p1.now()}`)

let p2 = new p1();
console.log(`p2 descriptors: ${Object.getOwnPropertyNames(Object.getPrototypeOf(p2))}`);
console.log(`p2.getFullYear(): ${p2.getFullYear()}`);

Post a Comment for "Javascript: Why Doesn't Proxy Intercept Methods"