Instance constructors
David Bruant
david.bruant at labri.fr
Fri Sep 23 16:20:12 PDT 2011
Le 24/09/2011 00:35, Allen Wirfs-Brock a écrit :
> let instance = Object.create(o);
> instance.constructor(/* constructor args */)
>
> This assumes that the new instance will inherit "constructor" from its prototype chain (possibly all the way to Object.prototype.constructor (.i.e. Object).
> If you are careful to always code your constructors to return this, you can shorten it to:
>
> let instance = Object.create(o).constructor(/* constructor args */);
>
> As I think I have talked about in the past. For ES.next I think we should extend the semantics of new to be approximately:
>
> function ESNewOperator( rhs, args) {
> if (rhs has [[Constructor]] ) return rhs.[[Constructor]].apply(undefined,args);
> let instance = Object.create(rhs);
> instance.constructor(...args);
> return instance;
> }
> ( a few additional error conditions need to be added)
>
> This allows the new operator to make sense (and work in an internally interoperable manner) for both prototypical and classical inheritance
>
> For example:
>
> let proto = {
> depth: 0;
> constructor: function() {this.depth += 1}; /* get parent's depth, increment it, and store as own property of instance */
> }
>
> let lev1 = new proto;
> let lev2 = new lev1;
> let lev3 = new lev2;
I love this!
David
More information about the es-discuss
mailing list