使用ES6代理捕获Object.hasOwnProperty

2023-12-25

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

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

但在审查之后代理文档 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy,我不知道该怎么做,主要是因为hastrap 陷阱是为了in运算符,上面的代码中似乎没有使用该运算符,并且没有陷阱hasOwnProperty手术。


您可以使用getOwnPropertyDescriptor handler https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor捕捉hasOwnProperty() calls.

Example:

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 指定的行为,而不是特定实现的怪癖:

  • Object.prototype.hasOwnProperty http://www.ecma-international.org/ecma-262/7.0/index.html#sec-object.prototype.hasownproperty调用摘要[[HasOwnProperty]]手术
  • [[HasOwnProperty]] http://www.ecma-international.org/ecma-262/7.0/index.html#sec-hasownproperty调用摘要[[GetOwnProperty]]手术
  • [[GetOwnProperty]]是什么getOwnPropertyDescriptor handles http://www.ecma-international.org/ecma-262/7.0/index.html#sec-proxy-object-internal-methods-and-internal-slots
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用ES6代理捕获Object.hasOwnProperty 的相关文章

随机推荐