new instantiation design alternatives
caitpotter88 at gmail.com
Mon Sep 15 18:10:57 PDT 2014
It’s just an example, but we recently changed Angular.js in such a way that we could pre-populate a controller instance (instantiated via user-specified constructor functions) with data before calling the constructor itself. This is a convenience, so that the data is readily available for the controller to use as soon as it begins its life.
Needless to say, returning an arbitrary value from the constructor doesn’t do what is expected, because the populated data isn’t re-configured for the newly returned value, and the return value is essentially ignored. It doesn’t have to work this way, but it does, and it would have been nice if returning values from constructors was never in the cards to begin with — similar to how it’s not possible in other languages. We essentially are using a version of placement new in JS, and it’s rather nice for providing these conveniences.
It’s fair to say we’re doing it wrong, but it’s hard to ignore the advantages/flexibility of it. What is the advantage of returning an arbitrary object from a constructor, other than being similar to JS as it is today?
On 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.
> es-discuss mailing list
> es-discuss at mozilla.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the es-discuss