How to test if an object is a Proxy?

后端 未结 13 2220
予麋鹿
予麋鹿 2020-11-30 07:23

I would like to test if a JavaScript object is a Proxy. The trivial approach

if (obj instanceof Proxy) ...

doesn\'t work here, nor does tra

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 07:44

    Adding 'support' for instanceof Proxy:

    I don't recommend it, but If you want to add support for instanceof, you could do the following before instantiating any Proxies:

    (() => {
      var proxyInstances = new WeakSet()
      
      // Optionally save the original in global scope:
      originalProxy = Proxy
    
      Proxy = new Proxy(Proxy, {
        construct(target, args) {
          var newProxy = new originalProxy(...args)
          proxyInstances.add(newProxy)
          return newProxy
        },
        get(obj, prop) {
          if (prop == Symbol.hasInstance) {
            return (instance) => {
              return proxyInstances.has(instance)
            }
          }
          return Reflect.get(...arguments)
        }
      })
    })()
    
    // Demo:
    
    var a = new Proxy({}, {})
    console.log(a instanceof Proxy) // true
    delete a
    
    var a = new originalProxy({}, {})
    console.log(a instanceof Proxy) // false
    delete a

提交回复
热议问题