JavaScript Constructor Pattern Native
by horhey
JavaScript
// constructor
var Rectangle = function(width, height) {
this.width = width;
this.height = height;
};
Rectangle.prototype.area = function() {
return this.width * this.height;
};
var myRect = new Rectangle(2, 2);
window.console.log('myRect area is %d', myRect.area()); // returns 4
// inheritance
var Square = function(size) {
Rectangle.call(this, size, size);
};
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
var mySquare = new Square(4);
window.console.log('mySquare area is %d', mySquare.area()); // returns 16