JavaScript Prototype Pattern
by horhey
JavaScript
// definition
var Rectangle = {
width: 0,
height: 0,
area: function () {
return this.width * this.height;
}
};
// native instantiation
var myRect = Object.create(Rectangle);
myRect.width = 2;
myRect.height = 2;
myRect.area(); // returns 4
window.console.log("1 myRect.area()=" + myRect.area());
// add create helper
Rectangle.create = function (width, height) {
window.console.log("in Rectangle.create()");
var obj = Object.create(this);
obj.height = height;
obj.width = width;
return obj;
};
// method instantiation
var myRect2 = Rectangle.create(4, 4);
window.console.log("2 myRect2.area()=" + myRect2.area()); // returns 16
//myRect2.area(); // returns 16
// inheritance
window.console.log("about to call Object.create(Rectancle)");
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
//cube
var Cube ;
Cube.length = 0;
Cube.create = function (side) {
this.height = side;
this.width = side;
this.length = side;
};
Cube.area = function () {
return height * width * length;
};
// 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,
...