Summary: prototypes as classes (PaCs)

Axel Rauschmayer axel at rauschma.de
Tue Jun 28 16:12:39 PDT 2011


> From: Bob Nystrom <rnystrom at google.com>
> Date: June 28, 2011 21:34:30 GMT+02:00
> Subject: Re: Summary: prototypes as classes


=== Class methods becoming instance methods ===

I agree: This one point is weirder with PaCs than with constructors. It would be great if global variables (as in “the global object”) wouldn’t have to be an instance of Object.

Two mitigating factors:
- This is how it already works in Java: Each instance can access all of the class methods.
- With PaCs, a subclass inherits all the superclass methods. That is something that e.g. CoffeeScript does manually, currently.

=== Target audience ===

I can accept compatibility with existing code as an argument in favor of constructors, but not that that’s what people are familiar with.

Explaining constructors-as-classes is really hard, explaining subclassing is even harder. PaCs bring significant simplifications in both areas. I don’t like the idea of having something that superficially looks simple (class literals as syntactic sugar for constructors-as-classes), but has the same old complexity under the hood.

I bet that in the coming year more new people are going to learn JavaScript than everyone who knows it now. We have to plan for former group, not for the latter.

=== Instantiation versus initialization ===

> Your proposal would allow that, I think. For example, starting from yours:
> 
>   // Superclass
>   var Person = {
>       constructor: function (name) {
>           this.name = name;
>       },
>       describe: function() {
>           return "Person called "+this.name;
>       }
>   };
> 
> I could do:
> 
>   var bob = new Person("Bob");
>   bob.constructor("Fred"); // I guess I'm Fred now.
> 
> Does the above seem strange to you too?

Note that your two lines work *exactly* the same with the following code (which is ES5 JavaScript):

function Person(name) {
    this.name = name;
}
Person.prototype.describe = function() {
  return "Person called "+this.name;
};

I do agree that it is a bit strange that the constructor is just another method. In a way, PaCs separate two concerns (that are muddled with constructor functions – see subclassing):

- Instantiation: Creating a new instance
- Initialization: Setting up a new instance

-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110629/c6990fe0/attachment.html>


More information about the es-discuss mailing list