JavaScript - The Definitve Guide - Chapter 9

9.2 A simple JavaScript class with constructor pattern

by Denise Nepraunig

JavaScript

// all examples are taken from JavaScript The Definitive Guide 6th Edition

// this is a factory function
function Range(from, to) {
    this.from = from;
    this.to = to;
}

// those prototype methods are inherited bay all range objects
Range.prototype = {
    // add the constructor to it
    constructor: Range,
    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 + ")";}
};

Range.prototype.hello = function() {
    console.log("Hello, I am range ;-)");
};

var r = new Range(1,3);
console.log(r.includes(2));
// somehow this console.log is silly
// r.foreach(console.log);
// but binding seems to work...
/* http://stackoverflow.com/questions/16615781/why-is-console-log-illegaly-invocated-as-a-function-parameter */
r.foreach(console.log.bind(console));
console.log(r);
r.hello();

var r2 = new Range(5,10);
console.log(r2);
console.log(r2.constructor);