new instantiation design alternatives

Rick Waldron waldron.rick at gmail.com
Tue Sep 16 07:55:44 PDT 2014


On Mon, Sep 15, 2014 at 8:37 PM, Alex Kocharin <alex at kocharin.ru> wrote:

>
>
> 15.09.2014, 23:23, "Rick Waldron" <waldron.rick at gmail.com>:
>
>
>
> On Mon, Sep 15, 2014 at 2:57 PM, Brendan Eich <brendan at mozilla.org> wrote:
>
> Rick Waldron wrote:
>
> The first is also objectionable because it breaks existing implicit return
> semantics.
>
> Say what? Constructors can return a different object from `this`, that's
> just JS.
>
>
> Yikes, I should've been more specific. Generally, it's considered an
> anti-pattern to write constructors that explicitly return an object to
> override `this`(for all the reasons you'd expect)—that's not to say that it
> isn't done or doesn't exist (and certainly I didn't mean to imply that it
> wasn't possible). Design that might rely on that pattern would conflict
> with widely accepted best practices.
>
>
>
> Writing constructors that override `this` is not an anti-pattern. It's an
> implementation detail that should not ever matter to any outside code.
>
> If your code breaks because somebody returns another object from
> constructor, you're doing it wrong.
>

Overriding `this` with an explicit return object will break the link to the
constructor's prototype object properties:

  function C() {
    return {};
  }

  C.prototype.m = function() {
    return "Previously on Lost";
  };

  var c = new C();

  console.log(c.m()); // nope.


Rick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20140916/efa46951/attachment-0001.html>


More information about the es-discuss mailing list