简体   繁体   English

如何在Javascript中检查es6代理的类型?

[英]How to check the type of es6 proxy in Javascript?

I am working with ES6 Proxy.我正在使用 ES6 代理。 I have created a proxy of an array, now when i check the type of proxy it is giving me as Object type.我已经创建了一个数组的代理,现在当我检查代理的类型时,它以Object类型的形式提供给我。

Question:题:

How can i check if the proxy i have created was for array or object?如何检查我创建的代理是用于数组还是对象?

Example:例子:

 const arr = ['a', 'b', 'c']; const arrProxy = new Proxy(arr, {}); alert(typeof(arrProxy));

UPDATE (SOLUTION): Instead of using typeof , we should use Array.isArray更新(解决方案):我们应该使用Array.isArray而不是使用typeof

const arr = ['a', 'b', 'c'];

const arrProxy = new Proxy(arr, {});

alert(Array.isArray(arrProxy));

You can't tell that a proxy is a proxy.你不能说代理是代理。 That's part of the point of them, they provide a facade (one you can't detect) around another object.这是它们的一部分,它们在另一个对象周围提供了一个外观(您无法检测到的外观)。

As far as code looking at your arrProxy can tell, it's an array:就查看您的arrProxy代码arrProxy ,它是一个数组:

 const arr = ['a', 'b', 'c']; const arrProxy = new Proxy(arr, {}); console.log(Array.isArray(arrProxy)); // true

Separately: typeof is very general, it gives you "object" for a huge range of things: Anything that's of an object (not primitive) type (including null ).另外: typeof非常通用,它为您提供了大量事物的"object" :任何属于对象(非原始)类型(包括null )的东西。 So typeof new Map() , typeof new Set() , typeof null , typeof document (on browsers), etc., will all give you "object" .所以typeof new Map()typeof new Set()typeof nulltypeof document (在浏览器上)等等,都会给你"object" (Also note that typeof is an operator, not a function; no need for the () in your code sample.) (另请注意, typeof是一个运算符,而不是一个函数;您的代码示例中不需要() 。)

There is also one way to do this using instanceof :还有一种方法可以使用instanceof做到这一点:

if (arrProxy instanceof Array) {
   console.log('This is an array!');
}

As other answers suggest, you cannot tell if something is a proxy.正如其他答案所暗示的那样,您无法判断某物是否是代理。

So you might need to implement it yourself.所以你可能需要自己实现它。

Here is an example from: https://exploringjs.com/deep-js/ch_proxies.html#transparent-virtualization-and-handler-encapsulation下面是一个例子: https : //exploringjs.com/deep-js/ch_proxies.html#transparent-virtualization-and-handler-encapsulation

const proxies = new WeakSet();

export function createProxy(obj) {
  const handler = {};
  const proxy = new Proxy(obj, handler);
  proxies.add(proxy);
  return proxy;
}

export function isProxy(obj) {
  return proxies.has(obj);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM