How to test if an object is a Proxy?

后端 未结 13 2121
予麋鹿
予麋鹿 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]) ...
    
    0 讨论(0)
  • 2020-11-30 07:54

    From http://www.2ality.com/2014/12/es6-proxies.html:

    It is impossible to determine whether an object is a proxy or not (transparent virtualization).

    0 讨论(0)
  • 2020-11-30 07:54

    The best method I have found is creating a weak set of the proxy objects. You can do this recursively when you are building and checking your proxied objects.

        var myProxySet = new WeakSet();
        var myObj = new Proxy({},myValidator);
        myProxySet.add(myObj);
    
        if(myProxySet.has(myObj)) {
            // Working with a proxy object.
        }
    
    0 讨论(0)
  • 2020-11-30 07:54

    It seems there is no standard way, but for Firefox privileged code you can use

    Components.utils.isProxy(object);
    

    For example:

    Components.utils.isProxy([]); // false
    Components.utils.isProxy(new Proxy([], {})); // true
    
    0 讨论(0)
  • 2020-11-30 07:57

    In Node.js 10 you can use util.types.isProxy.

    For example:

    const target = {};
    const proxy = new Proxy(target, {});
    util.types.isProxy(target);  // Returns false
    util.types.isProxy(proxy);  // Returns true
    
    0 讨论(0)
  • 2020-11-30 07:57

    In fact, there is workaround for determine if object is proxy, which is based on several assumptions. Firstly, Proxy determination can be easily solved for node.js environment via C++ extensions or privileged web-page in browser, when page can launch unsecure extensions. Secondly, Proxy is relative new functionality, so it does not exist in old browsers - so solution works only in modern browsers.

    JS engine can't clone functions (Since they have bindings to activation context and some other reasons), but Proxy object by definition consists of wrapper handlers. So to determine if object is proxy, it's enough to initiate force object cloning. In can be done via postMessage function.

    If object is Proxy, it will failed to copy even it does not contain any functions. For example, Edge and Chrome produces following errors while try to post Proxy object: [object DOMException]: {code: 25, message: "DataCloneError", name: "DataCloneError"} and Failed to execute 'postMessage' on 'Window': [object Object] could not be cloned..

    0 讨论(0)
提交回复
热议问题