How to test if an object is a Proxy?

后端 未结 13 2221
予麋鹿
予麋鹿 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:51

    Create a new symbol:

    let isProxy = Symbol("isProxy")
    

    Inside the get method of your proxy handler you can check if the key is your symbol and then return true:

    get(target, key)
    {
        if (key === isProxy)
            return true;
    
        // normal get handler code here
    }
    

    You can then check if an object is one of your proxies by using the following code:

    if (myObject[isProxy]) ...
    

提交回复
热议问题