Summary: prototypes as classes

Axel Rauschmayer axel at rauschma.de
Tue Jun 28 17:19:01 PDT 2011


As an aside:
- Static methods in Java always felt like a hack, because Java’s creators couldn’t bring themselves to support first-class functions.
- Thus: I would much prefer to put Object.* methods into a module (once we have those). The same holds for “class methods” such as Math.*. There Math is used for namespacing and not really a class.

> From my view, JS-of-today is no less prototype-based than what Axel is proposing, it just wires things up a bit differently. Or is there something I'm missing?


I agree. However: Prototypes are already *the* core mechanism with regard to JS inheritance, they are what stays after an instance has been created, they are actually used for instanceof tests, etc. PaCs put more emphasis on them, that’s all. I find they really shine when it comes to subclassing. You have to work harder with constructor functions (super-references will help a little, though). See code below. To me, the prototypes are at the core of what is happening in subclassing.

== Prototypes as classes ==

    // Superclass
    var Person = {
        constructor: function (name) {
            this.name = name;
        },
        describe: function() {
            return "Person called "+this.name;
        }
    };

    // Subclass
    var Worker = Person <| {
        constructor: function (name, title) {
            Person.constructor.call(this, name);
            this.title = title;
        },
        describe: function () {
            return Person.describe.call(this)+" ("+this.title+")"; // (*)
        }
    };
    
== Constructor functions ==

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

    // Subclass
    function Worker(name, title) {
        Person.call(this, name);
        this.title = title;
    }
    Worker.prototype = Person.prototype <| {
        constructor: Worker,
        describe: function() {
            return Person.prototype.describe.call(this)+" ("+this.title+")";
        }
    };


-- 
Dr. Axel Rauschmayer

axel at rauschma.de
twitter.com/rauschma

home: rauschma.de
blog: 2ality.com





More information about the es-discuss mailing list