JavaScript Prototype Pattern

by anandhinava

JavaScript

// definition
var Rectangle = {
    width: 0,
    height: 0,
    area: function () {
        return this.width * this.height;
    },
    perimeter : function() {
        return 2 * this.width + 2 * this.height;
    }
};

// native instantiation
var myRect = Object.create(Rectangle);
myRect.width = 2;
myRect.height = 2;
myRect.area(); // returns 4
myRect.perimeter();

// add create helper 
//This is a constructor that takes width and height
Rectangle.create = function (width, height) {
    var obj = Object.create(this);
    obj.height = height;
    obj.width = width;
    return obj;
};

// method instantiation
var myRect2 = Rectangle.create(4, 4);
myRect2.area(); // returns 16
myRect2.perimeter();

// inheritance
var Square = Object.create(Rectangle);

// override create to copy single dimension to width/height
Square.create = function (side) {
    return Rectangle.create.call(this, side, side);
};

var mySquare = Square.create(8);
mySquare.area(); // returns 64
mySquare.perimeter();

// helper method to extend objects easily
Object.prototype.extend = function (def) {
    var obj = Object.create(this),
        prop;
    for (prop in def) {
        if (
        Object.hasOwnProperty.call(def, prop) || obj[prop] === undefined) {
            obj[prop] = def[prop];
        }
    }
    obj.$super = this;
    return obj;
};

var AnotherSquare = Rectangle.extend({
    create: function (side) {
        return this.$super.create.call(this, side, side);
    }
});

var myAnotherSquare = AnotherSquare.create(16);
myAnotherSquare.area(); // returns 256

// overwrite extend to allow for mixins
Object.prototype.extend = function () {
    var obj = Object.create(this),
        length = arguments.length,
        index = length,
        args = Array.prototype.slice.call(arguments),
        def,
        prop;
    args.forEach(function (def) {
        for (prop in def) {
            if (Object.hasOwnProperty.call(def, prop) || obj[prop] === undefined) {
                obj[prop] =...