Polyfilling Object.observe

Alex Vincent ajvincent at gmail.com
Sat Jul 28 15:54:00 UTC 2018

> `Proxy` is powerful, but it's not as good as `Object.observe` would've
> been for some very simple tasks.
> Every time I wish I could use `Proxy` in a simple way, there's always some
> issue with it. For example: https://jsfiddle.net/trusktr/hwfontLc/17

Because you are doing it wrong.

Proxies can *only* observe on the object that they're created for.  By
setting Foo.prototype to a proxy, you can only observe operations on
Foo.prototype, not instances of Foo.

What you really want is to have new Foo() return a Proxy... which is
counter-intuitive, admittedly, because we're all taught that a constructor
should never explicitly return a value.

This problem has been solved, a few times, with the introduction of
membranes in JavaScript.  In that environment, you would start with Foo and
wrap it in a membrane proxy. Then, in invoking new Foo(), the "construct"
trap of that proxy would return another roxy automatically, probably using
the same proxy handler but a different proxy target.

If it's any consolation, proxies are in general very hard to work with.
You're only scratching the surface here.  I recently gave a talk at TC39
(the standards body for ECMAScript) on membranes.  One key takeaway is that
the overhead in dealing with membrane-oriented proxies really is better off
left to a library built for that purpose.

Tom van Cutsem is working on an article summarizing the current state of
membranes.  I'm not sure if he has approved its general release yet, so
stay tuned...

Alex Vincent
Edmonds, WA (on vacation)

"The first step in confirming there is a bug in someone else's work is
confirming there are no bugs in your own."
-- Alexander J. Vincent, June 30, 2001
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180728/01cf314e/attachment.html>

More information about the es-discuss mailing list