Subclassing ES6 objects with ES5 syntax.
Kevin Smith
zenparsing at gmail.com
Wed Apr 29 18:40:01 UTC 2015
>
> const goodPromises = new WeakSet();
> class DefensivePromise {
> constructor(x) {
> super(x);
> if (new.target === DefensivePromise) {
> Object.freeze(this);
> goodPromises.add(this);
> }
> }
> static resolve(x) {
> if (goodPromises.has(x)) {
> return x; // should be equiv to super.resolve(x);
> }
> return new DefensivePromise(r => {r(x)});
> }
> }
>
>
Basically you can't rely on new.target to mean what you think it means, in
the face of Reflect.construct.
Maybe this?
constructor(x) {
super(x);
// At this point you know that "this" is a Promise, but you don't
// know if the prototype is set correctly, so:
if (Object.getPrototypeOf(this) === DefensivePromise.prototype)
gooPromises.add(Object.freeze(this));
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150429/0ace8743/attachment.html>
More information about the es-discuss
mailing list