I noted some open issues on "Classes with Trait Composition"

Andreas Rossberg rossberg at google.com
Thu May 19 05:36:44 PDT 2011

My apologies if this has been discussed to death before -- well,
actually, I'd be surprised if it hasn't (pointers would be welcome).

I think it is worth noting that the baroque notation for defining
constructors that we see in the C++ / Java / C# world primarily is an
artefact of the desire to allow multiple constructors with overloading
in those languages. We don't have that issue in JS, so I wonder why we
cannot go for something more elegant? There is precedent in other
OOPLs (off the top of my head, e.g. Scala and OCaml) for putting the
constructor arguments on the class head directly, and executing the
class body like a block when the constructor is invoked. AFAICS:

-- This approach is significantly slimmer (and, I'd argue, more
readable) than the discussed alternatives, without needing any

class Point(x0, y0) {
  public x = x0
  public y = y0

-- It naturally allows what Bob was suggesting:

class Point {  // no argument list would be shorthand for (), just
like when invoking new
  public x = 0
  public y = 0

-- It avoids additional hoops with initializing const attributes:

class ImmutablePoint(x0, y0) {
  const x = x0  // just like elsewhere
  const y = y0

-- The constructor arguments naturally are in the scope of the entire
object, so often you do not even need to introduce explicit (private)
fields to store them:

class Point(x, y) {
  public function abs() { return Math.sqrt(x*x, y*y) }


On 19 May 2011 03:31, Mark S. Miller <erights at google.com> wrote:
> On Wed, May 18, 2011 at 6:29 PM, Brendan Eich <brendan at mozilla.com> wrote:
>> On May 18, 2011, at 5:57 PM, Bob Nystrom wrote:
>> class Point {
>>   public x = 0, y = 0;
>> }
>> let p = new Point();
>> p.x; // 0
>> This is pretty rare, in my experience. A hard case? If the constructor
>> does set x and y from parameters, then you have double-initialization. If
>> some properties are non-writable, you can't do this. YAGNI?
> +1. If you're gonna initialize them somewhere, why not always do so in the
> constructor and avoid special cases?
>> /be
> --
>     Cheers,
>     --MarkM
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

More information about the es-discuss mailing list