Search code examples
javascriptecmascript-6hasownpropertyes6-proxy

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 (!Object.prototype.hasOwnProperty.call(obj, 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 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.


Solution

  • You can use the getOwnPropertyDescriptor handler to capture 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 specified behavior, not a quirk of a particular implementation: