4

I know how to intercept get`set` and such within a proxy using the following code:

function get( target, prop, receiver ) {
  console.log("Intercepted get")
  return Reflect.get( target, prop, receiver );
}
var handler = {
  'get': get
};
var proxy = new Proxy( new Array(...[7, 1,2,3,4,5]), handler );

I'm unable to replicate this for sort. Adding:

function sort(target, prop) {
  console.log("Intercepted sort")
  return Reflect.sort(target);
}
var handler = {
  'get': get,
  'sort': sort
};

Doesn't work. I've also been unable to find documentation. How do I intercept the sort function?

Blue Granny
  • 772
  • 1
  • 8
  • 24
  • The first snippet works just fine. `proxy.sort();` displays `Intercepted get` several times. There is no `sort` handler. The [documentation](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy/Proxy#handler_functions) is on MDN. – Sebastian Simon Oct 13 '21 at 09:11

1 Answers1

4

You have to use get to trap methods. get is called for each property and each method that is read. The name of the property or method is passed into get as second argument prop:

function sort() {
  console.log("Intercepted sort")
  return this.sort();
}
function get( target, prop, receiver ) {
  if (prop === 'sort') {
    return sort.bind(target);
  }
  console.log("Intercepted get")
  return Reflect.get( target, prop, receiver );
}
var handler = {
  get
};
var proxy = new Proxy( new Array(...[7,1,2,3,4,5]), handler );
console.log(proxy.sort())
jabaa
  • 5,844
  • 3
  • 9
  • 30
  • How do I capture the function passed to the sort? I can't see it in the receiver property. – Blue Granny Oct 20 '21 at 18:39
  • @BlueGranny You don't capture the function call. You capture the function access. You have to return a function, that expects a callback function. In my code I return `sort.bind(target)`. In JavaScript methods are just basic functions with a specific `this` context (that's a little bit simplified). The proxy doesn't have access and can't modify the actual function call. – jabaa Oct 21 '21 at 08:11