JavaScript Prototype Pattern
by vijayram_a
JavaScript
// definition -- class?
var Rectangle = {
width: 0,
height: 0,
area: function () {
return this.width * this.height;
},
diagonal: function() {
return this.width + this.height; //sqrt function?
}
};
// native instantiation
var myRect = Object.create(Rectangle); // similar to java new Class()?
myRect.width = 2;
myRect.height = 2;
myRect.area(); // returns 4
myRect.diagonal();
// add create helper
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
// 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
//--------------------------------------------------------------------
// 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) {
...