JavaScript Prototype Pattern
by ramyaaviji
JavaScript
// definition
var Rectangle = {
width: 0,
height: 0,
area: function () {
return this.width * this.height;
},
perimeter: function () {
return this.width + this.height + this.width + this.height;
}
};
// native instantiation
var myRect = Object.create(Rectangle);
myRect.width = 2;
myRect.height = 2;
myRect.area();
myRect.perimeter();// returns 4
window.console.log(myRect.perimeter());
// 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) {
window.console.log(prop);
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
window.console.log(myAnotherSquare.perimeter());
// 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]...