Wishfull thinking: classes

2011-11-03

Let's just get right down to it. There's a lot of debate about class syntax in the next version of JS. Here's my two cents. Who knows, maybe somebody actually likes its simplicity and easy learning curve. There are some notes below.

Simple classes:

Code:
class Person {
constructor: function(){
console.log("Person");
},
foo: null,
bar: function(){},

}

Would desugar exactly to:
Code:
function Person(){
console.log("Person");
}
Person.prototype = {
foo: null,
bar: function(){}
};


Expanding a class:

Code:
expand Person {
meh: bla,
bida: function(){}
}

Would desugar to...
Code:
Person.prototype.meh = bla;
Person.prototype.bida = function(){};

Or something like this:
Code:
for (var key in obj) Person.prototype[key] = obj[key];


Subclassing:

Code:
class A {
constructor: function(){},
foo: 5,
bar: function(){}
}

class B extends A { // this would not invoke A, unlike the desugared version would
constructor: function(){
super(); // A, or first parent up the prototype chain
},
baz: 20,
boo: function(){}
}
class C extends B { // this would not invoke A or B, unlike the desugared version would
constructor: function(){
super();
A.call(this);
}
}

Would almost desugar to the following. Changed to use Object.create. Thanks David and Christian :)

Code:
function A(){}
A.prototype = {
foo: 5,
bar: function(){}
};

function B(){ A.call(this); }
B.prototype = Object.create(A.prototype);
B.prototype.baz = 20;
B.prototype.boo = function(){};

function C(){
B.call(this);
A.call(this);
}
C.prototype = Object.create(B.prototype);


The "constructor" name for the class constructor could also be the class name. But I think that's just silly. You're repeating the class name? Why not just codify "constructor" as being it. I think it's cleaner and you'll immediately know where to look for, rather than the same name as the class. I also feel the need for adding syntax for explicitly defining both the constructor and the regular function. But at the same time I'm thinking no, why bother.

It feels like I use the expanding syntax a lot, although in these examples that would be mitigated due to the new class syntax. Regardless, I think it's still desirable to have easy syntax to expand an existing class somehow, without repeating the assignments. And no, that's not what I have subclassing for :)

Also, there are no privates in this proposal. I really don't need privates but then again, I'm probably not the right one to comment on that for that same reason. However, I think adding privates to the syntax will make it both complicated and ugly.

Another thing missing is interfaces. I don't think that's something for JS right now. Interfaces imply some sort of type checking. A mechanism that's completely not part of the spec.

So yeah. I hope that whatever the class syntax ends up being, it tries to keep JS the same language, without having to introduce heavy weird shit.ok