How to test if an object is a Proxy?

In my current project I also needed a way of defining if something was already a Proxy, mainly because I didn’t want to start a proxy on a proxy. For this I simply added a getter to my handler, which would return true if the requested variable was “__Proxy”:

function _observe(obj) {
  if (obj.__isProxy === undefined) {
    var ret = new Proxy(obj || {}, {
      set: (target, key, value) => {
        /// act on the change
        return true;
      },
      get: (target, key) => {
        if (key !== "__isProxy") {
          return target[key];
        }

        return true;
      }
    });
    return ret;
  }

  return obj;
}

Might not be the best solution, but I think it’s an elegant solution, which also doesn’t pop up when serializing.

Leave a Comment