Prototypes as the new class declaration

Axel Rauschmayer axel at rauschma.de
Sun Jun 19 10:01:05 PDT 2011


>>  - Object.getPrototypeOf(obj).constructor: should it always point to the constructor? Or is it a reference to a class construct (either old-style or new-style)? Most of the code will probably only use it as the operand of the "new" operator.
> 
> I'm not sure what you mean here. The 'constructor' property of prototype objects is writable, but overwriting it could be a useful technique. It's unlikely to be accidentally clobbered, but user-defined and unfrozen function objects can have their .prototype properties overwritten too, so there' s no greater integrity problem in relying on .constructor compared to .prototype for user-defined functions.

Sorry, that was me misunderstanding your previous answer: I thought that one could have an abstraction called “class” denoting a factory for instances. An old-style class would be a function (constructor -> prototype), a new-style class would be a non-function object (prototype -> constructor). Once you have that abstraction, you have to fulfill the expectations of existing code. One of those expectations is that you can apply "new" to the property "constructor" of the prototype of an object to create a new instance. Thus, that property would have to point to the class (either old-style or new-style) that originally produced the object.

>>  - o instanceof C: treat non-function operands differently. Then simply desugars to C.isPrototypeOf(o).
> 
> The details matter. Currently instanceof layers on spec-internal [[HasInstance]], implemented in the spec only by Function objects. We could add [[HasInstance]] for all objects that does as you say: tests this.isPrototypeOf(o) for argument o (the left operand of instanceof; |this| refers to the right operand). But do we want to add [[HasInstance]] for all objects?
> 
> Or we could check for Y.constructor (object-detect it, as it were) in the x instanceof Y semantics, and use that property's value instead of Y as |this| when calling [[HasInstance]]. This is less efficient and at the limit less reliable given the writability of .constructor.

Right. It probably doesn’t matter how it is handled internally, as long as we can pretend externally that o instanceof C means “look for C in the prototype chain of o”. IMHO that would make things much easier to understand for newbies.

Right now, JS inheritance is hard to understand and hard to explain (especially subclassing). With “prototypes as classes”, a proto operator (such as <|) and "super", we would have a long-term simplification that to me almost feels like a clarification of what is going on already.

Axel

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com



More information about the es-discuss mailing list