Classes and Prototypes

In Javascript, a class is a set of objects that inherit properties from the same protoype object.

function range(from, to) {
    var r = inherit(range.methods);
    r.from = from;
    r.to = to;
    return r; 
}
range.methods = {
    includes: function(x) { 
        return this.from <= x && x <= this.to; 
    },
    foreach: function(f) {
        for(var x = Math.ceil(this.from); x <= this.to; x++) 
            f(x); 
    },
    toString: function(){
        return "(" + this.from + "..." + this.to + ")"; 
    }
}
var r = range(1,3); 
r.includes(2); 
r.foreach(console.log); 
console.log(r);

Classes and Constructors

function Range(from, to) {
    this.from = from;
    this.to = to;
}
Range.prototype = {
    includes: function(x) { 
        return this.from <= x && x <= this.to; 
    },
    foreach: function(f) {
        for(var x = Math.ceil(this.from); x <= this.to; x++) 
            f(x); 
    },
    toString: function(){
        return "(" + this.from + "..." + this.to + ")"; 
    }
}
var r = new Range(1,3); 
r.includes(2); 
r.foreach(console.log); 
console.log(r);

Constructors and Class Identity

the prototype object is fundamental to the identity of a class

    r instanceof Range // returns true if r inherits from Range.prototype

The constructor Property

common technique is to use the predefined prototype object with its constructor property, and add methods to it one at a time:

    // Extend the predefined Range.prototype object so we don't overwrite
    // the automatically created Range.prototype.constructor property.

    Range.prototype.includes = function(x) { 
        return this.from<=x && x<=this.to; 
    };
    Range.prototype.foreach = function(f) {
        for(var x = Math.ceil(this.from); x <= this.to; x++) 
        f(x); 
    };
    Range.prototype.toString = function() {
        return "(" + this.from + "..." + this.to + ")";
    };