es6-proxy

Why console.log receiver value in get handler cause an error?


I am learning ES6 Proxy, and try to understand param 'receiver' in a get trap, so I tried to console.log the receiver value. But when run in nodeJS, it causes an error:

RangeError: Maximum call stack size exceeded

let proxy = new Proxy({}, {
  get (target, key, receiver) {
    console.log('receiver:', receiver)
  }
})
let obj = Object.create(proxy)
console.log(obj)

I want to know what is causing this error, and how to test receiver's reference in different situations.


Solution

  • The receiver in get (target, key, receiver) refers to the Proxy object, so you create an endless loop.

    console.log(obj) tries to log the contents of obj, so it is iterating over all its keys, and retrieves their value. To get their value, the get of the Proxy is invoked, and in that get you have console.log('receiver:', receiver), and there receiver refers to obj, so again it tries to log the contents of obj, … which results in an endless recursive loop.

    If you want to understand the param receiver in a get trap then you should not use logging, but the debugger, breakpoints, and the variable inspector in the debugger.