Not own property getters

T.J. Crowder tj.crowder at farsightsoftware.com
Fri Sep 8 07:50:31 UTC 2017


On Fri, Sep 8, 2017 at 2:28 AM, Alex Kodat
<alexkodat at gmail.com> wrote:
> Head slap. The following does what I want with essentially zero
> overhead (at least with V8)...

:-) Clever solution for situations where you can't detect these statically
in advance, nice one.

You can turn it up to 11 by avoiding hitting the proxy for the
`Object.property` properties, by making the base guard prototype derive
from your proxy and put the `Object.property` features on it. That way,
`hasOwnProperty`, `valueOf`, etc. aren't impacted by passing through the
proxy. (See my `Guarded` below.)
https://jsperf.com/throw-on-missing-property-scenarios

You'll also want to handle `toJSON` and other spec-defined optional
properties or properties implementations commonly look for outside spec (is
that what your `inspect` property is?). And set `constructor`.

```js
function Guarded() {
}
Guarded.prototype = Object.create(new Proxy(Object.freeze(Object.create(null)),
{
  get: (target, prop) => {
    if (prop === "toJSON" || prop === "inspect") {
        return undefined;
    }
    throw Error("Bad property: " +  prop);
  }
}));
Object.defineProperties(Guarded.prototype, Object.getOwnPropertyDescriptors(
Object.prototype));
Object.defineProperty(Guarded.prototype, "constructor", {
    value: Guarded,
    configurable: true
});

class Foo extends Guarded {}
```

-- T.J. Crowder
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20170908/17e43125/attachment.html>


More information about the es-discuss mailing list