Proposal: allow primitives to be explicitly returned from constructors

T.J. Crowder tj.crowder at farsightsoftware.com
Fri Apr 20 16:06:06 UTC 2018


On Thu, Apr 19, 2018 at 11:49 PM, Isiah Meadows <isiahmeadows at gmail.com>
wrote:
>
> Here's my proposal:
>
> In constructors, currently, non-objects are replaced with `this`.
> Here's what I think it should be replaced with:
>
> 1. When calling the constructor, if `undefined` is returned and
> `new.target` is not `undefined`, return `this` instead. This is for
> compatibility and ease of implementation.
> 1. When calling the constructor, if anything else is returned, return
> that value in raw form.

I think you'll struggle to demonstrate that this is web-safe; certainly
doing so would be a major undertaking.

One particular habit that would be of concern is people writing:

```js
if (condition) return someFunction();
```

instead of

```js
if (condition) {
    someFunction();
    return;
}
```

...when they know full well that they don't actually want to return the
result of `someFunction`. Mostly I see that in Node-style callbacks where
the return value is ignored, but it wouldn't surprise me at all if there
was code in the wild that did that in a constructor, happily (and probably
unintentaionally) taking advantage of the fact that the return value will
be ignored.

Horribly contrived example:

```js
class Multiplier {
    constructor(a, b) {
    if (typeof a === "undefined") {
      this.setA(7);
      return this.setB(6);
    }
    this.setA(a);
    this.setB(b);
  }
  setA(value) {
    return this.a = value;
  }
  setB(value) {
    return this.b = value;
  }
  execute() {
    return this.a * this.b;
  }
}
const m = new Multiplier();
console.log(m.execute());
```

And just generally, changing a behavior that's so well-established without
some kind of mode (and I'm told There Will Be No More Modes) seems like
asking for trouble. Would need to have a massive, unambiguous benefit.

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


More information about the es-discuss mailing list