GregRos GregRos - 1 year ago 226
Javascript Question

Use ES6 proxy to trap Object.hasOwnProperty

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

for (let key in trapped) {
if (!, key)) continue;
let value = trapped[key];
//various code

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

Answer Source

You can use the getOwnPropertyDescriptor handler to capture hasOwnProperty() calls.


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

const hasOwn = Object.prototype.hasOwnProperty;

console.log(, 'a'));
console.log(, 'b'));

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download