Summary: prototypes as classes

Bob Nystrom rnystrom at google.com
Tue Jun 28 12:34:30 PDT 2011


I like the simplicity of this, but I'm not crazy about how it merges two
distinct objects into one. TodayJS (and most class-based languages) let you
distinguish two things:

1. A set of properties relevant to the class itself.
2. A set of properties shared by each instance of the class.

In a class-based language, #1 up there is "static" methods and fields. So
when you do something like this in Java:

  Integer.parseInt("1234");

The "parseInt" method isn't a method that you can call on an integer, it's a
method you call on the Integer class itself.

In Javascript, those are properties on the constructor:

  function Point(x, y) {
    this.x = x; this.y = y;
  }

  Point.zero = function() { return new Point(0, 0); }

  Point.zero(); // "static" method.

The second set of properties are properties on ".prototype" in JS:

  Point.prototype.flipX = function() {
    this.x = -this.x;
  }

  var p = new Point(1, 2);
  p.flipX();
  p.x // -1

To me, those two sets are utterly distinct. This code looks pretty strange:

  Point.flipX(); // What x?

  var p = new Point(1, 2);
  p.zero(); // This works, but what does it have to do with 'p'?

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?

- bob

On Sat, Jun 25, 2011 at 1:11 PM, Axel Rauschmayer <axel at rauschma.de> wrote:

> FWIW: I’ve written down my current understanding.
>
> http://www.2ality.com/2011/06/prototypes-as-classes.html
>
> --
> Dr. Axel Rauschmayer
>
> axel at rauschma.de
> twitter.com/rauschma
>
> home: rauschma.de
> blog: 2ality.com
>
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110628/81cb05df/attachment.html>


More information about the es-discuss mailing list