使用ES6代理来捕获Object.hasOwnProperty [英] Use ES6 proxy to trap Object.hasOwnProperty

查看:510
本文介绍了使用ES6代理来捕获Object.hasOwnProperty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用ES6代理来捕获以下通用代码:

I want to use an ES6 proxy to trap the following common code:

for (let key in trapped) {
    if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;
    let value = trapped[key];
    //various code
}

但在查看代理文档,我不确定该怎么做,主要是因为 has 陷阱陷阱是针对 in 运算符的,在上面的代码中似乎没有使用并且 hasOwnProperty 操作没有陷阱。

But after reviewing the proxy documentation, I'm not sure how to do it, mainly because the has trap trap is for the in operator, which does not seem to be used in the above code and there is no trap for the hasOwnProperty operation.

推荐答案

使用 getOwnPropertyDescriptor 处理程序捕获 hasOwnProperty()调用。

示例:

const p = new Proxy({}, {
  getOwnPropertyDescriptor(target, property) {
    if (property === 'a') {
      return {configurable: true, enumerable: true};
    }
  }
});

const hasOwn = Object.prototype.hasOwnProperty;

console.log(hasOwn.call(p, 'a'));
console.log(hasOwn.call(p, 'b'));

这是指定的行为,而不是具体实现方式:

This is specified behavior, not a quirk of a particular implementation:

  • Object.prototype.hasOwnProperty calls the abstract [[HasOwnProperty]] operation
  • [[HasOwnProperty]] calls the abstract [[GetOwnProperty]] operation
  • [[GetOwnProperty]] is what getOwnPropertyDescriptor handles

这篇关于使用ES6代理来捕获Object.hasOwnProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆