prototype focus

Peter Michaux petermichaux at gmail.com
Thu Jun 30 12:54:47 PDT 2011


There seems to have been a lot of fuss here about focusing on
prototypes first rather than on constructor functions. As it stands
now, I don't see how JavaScript makes focusing on prototypes
difficult.

// focus on the prototype first
// Make it non-abstract.
// Call it "zero" not "number".
// (Another example: Call the object "adam" not "person".)

var zero = {
    realPart: 0,
    imagPart: 0,
    getMagnitude: function() {
        return Math.sqrt(this.realPart * this.realPart +
                         this.imagPart * this.imagPart);
    }
};

// JavaScript makes it possible to have a variety of constructors
// for objects that have zero as their prototype.
// Yes the constructor property is gone. Is that actually a problem?

function Real(r) {
    this.realPart = r;
}
Real.prototype = zero;

function Imaginary(i) {
    this.imagPart = i;
}
Real.prototype = zero;

function Complex(r, i) {
    this.realPart = r;
    this.imagPart = i;
}
Complex.prototype = zero;

// Now make some objects.

var two = new Real(2);
var i = new Imaginary(2);
var oneone = new Complex(1, 1);

Isn't that prototype-focused enough?

Peter


More information about the es-discuss mailing list