繁体   English   中英

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

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

我正在使用 ES6 代理。 我已经创建了一个数组的代理,现在当我检查代理的类型时,它以Object类型的形式提供给我。

题:

如何检查我创建的代理是用于数组还是对象?

例子:

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

更新(解决方案):我们应该使用Array.isArray而不是使用typeof

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

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

alert(Array.isArray(arrProxy));

你不能说代理是代理。 这是它们的一部分,它们在另一个对象周围提供了一个外观(您无法检测到的外观)。

就查看您的arrProxy代码arrProxy ,它是一个数组:

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

另外: typeof非常通用,它为您提供了大量事物的"object" :任何属于对象(非原始)类型(包括null )的东西。 所以typeof new Map()typeof new Set()typeof nulltypeof document (在浏览器上)等等,都会给你"object" (另请注意, typeof是一个运算符,而不是一个函数;您的代码示例中不需要() 。)

还有一种方法可以使用instanceof做到这一点:

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

正如其他答案所暗示的那样,您无法判断某物是否是代理。

所以你可能需要自己实现它。

下面是一个例子: 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