jeudi 29 septembre 2022

Proxy js object: where are defined arguments when calling a function using Reflect.get()

Trying to understand the internals of Proxy and Reflect built-in objects, I've reached - IMO - an interesting "how does this even work" point:

Let's say I want to wrap into a Proxy this object and detect when we're accessing a callable property:

const obj = {
 v: 42,
 foo(n) { return this.v + n }
} 
const pObj = new Proxy(obj, {
  get(target, prop, r) {
    if (typeof target[prop] === 'function') {
      console.log('accessing a function, arguments: ', { ...arguments })
    }
    return Reflect.get(...arguments);
  }
}) 

This code just works:

pObj.foo(1000) // « 1042

Printing this trace:

trace when calling the function

Which reads: arguments has

  • target ([0]): the object
  • prop ([1]): "foo"
  • receiver ([2]): the proxy object itself.

My question is, where is defined the function argument (1000) that is applied to foo(n)? isn't defined in arguments? is it possible to validate this argument before calling Reflect.get(...arguments)?





Aucun commentaire:

Enregistrer un commentaire