The class operator: a bridge between object and function exemplers
Irakli Gozalishvili
rfobic at gmail.com
Tue Nov 15 09:48:59 PST 2011
Sorry I'm so excited about this that I just could not read it all before posting this, my apologies if it's already discussed:
On Monday, 2011-11-14 at 17:04 , Allen Wirfs-Brock wrote:
> > > >
> > > > UnaryExpression :
> > > > class UnaryExpression
> > > > ...
> > > >
> > > > The semantics are:
> > > > 1. if UnaryExpression is undefined or null, return the value of UnaryExpression.
> > > > 2. Let obj be ToObject(UnaryExpression)
> > > > 3. Return the result of calling the [[Get]] internal method of obj with argument 'constructor'
> > > >
> > >
> > >
> > > Interesting, so 'constructor' will inherit from Object.prototype if missing from the exemplar. This means
> > >
> > > let Point = class {
> > > x:0,
> > > y,0
> > >
> > > };
> > >
> > > let p = new Point(1, 2);
> > >
> > > will result in p being constructed via the equivalent of new Number(1).
> >
>
> sh*t! I though I'd had a solution for this, but maybe I don't...
>
> If you are really going to define either an object or class exemplar, you really need to define a constructor. The object exemplar case actually works out ok in this case because the inherited constructor is "called as a function", not "as a constructor". So for
>
> let Point = {
> x: 0,
> y: 0
> };
> let p = new Point(1,2);
>
> Is pretty much equivalent to:
> let p = Point <| {};
>
> which may not be exactly what the programmer expected but it is a least in the vicinity and yields an object with (inherited) x and y properties.
I think this concern could be easily fixed if `class prototype` was equivalent of `Class(prototype)` where implementation of Class is following (BTW I don't propose to use Class function just illustration of what class prototype could be) :
function Class(prototype) {
function constructor() {
Object.hasOwnProperty(prototype, 'constructor')
let instance = Object.create(prototype);
instance.constructor.apply(instance, arguments);
return instance;
}
constructor.prototype = prototype;
return constructor;
}
As additional benefit this solves issue of shared / frozen constructor properties of the prototype.
P.S.: I just yesterday I started experimenting with `Class` function in combination with selfish.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20111115/1bbfe607/attachment-0001.html>
More information about the es-discuss
mailing list