使用ES6代理捕获Object.hasOwnProperty

Gre*_*Ros 2 javascript hasownproperty ecmascript-6 es6-proxy

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

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

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

Mic*_*ski 10

您可以使用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'));
Run Code Online (Sandbox Code Playgroud)

这是指定的行为,而不是特定实现的怪癖: