如何判断元素是被proxy代理过的呢?

案例:

let arr = [];
let proxyer = new Proxy(arr, {});
console.log(proxyer instanceof Proxy); // 报错:Uncaught TypeError: Function has non-object prototype 'undefined' in instanceof check
console.log(proxyer instanceof Array); // true
console.log(proxyer.__proto__.constructor); // Array() { [native code] }

new Proxy的实例和被代理的taget保持相同的引用类型,Proxy的实例的原型上也没有所谓的Proxy构造函数

那么如何判断一个元素是proxy类型呢?

使用Symbol.toStringTag

在这里插入图片描述
通俗理解就是可以改变Object.prototype.toString的执行结果

// 例一
({[Symbol.toStringTag]: 'Foo'}.toString())
// "[object Foo]"

// 例二
class Collection {
  get [Symbol.toStringTag]() {
    return 'xxx';
  }
}
let x = new Collection();
Object.prototype.toString.call(x) // "[object xxx]"
最终解决方案
Proxy = new Proxy(Proxy, {
  //拦截 new 操作符,生成 Proxy 实例的时候来拦截
  construct: function (target, argumentsList) {
    //result是new Proxy()生成的原本的实例
    const result = new target(...argumentsList);
    //获取原本实例reslut的类型
    const originToStringTag = Object.prototype.toString.call(result).slice(1,-1).split(' ')[1]
    //改写result的[Symbol.toStringTag]属性,加上被代理的标志
    result[Symbol.toStringTag] = 'Proxy-' + originToStringTag;
    return result;
  },
});
let a = new Proxy([],{})

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值