Skip to content

Instantly share code, notes, and snippets.

@michaeljacobdavis
Created December 13, 2012 00:33
Show Gist options
  • Save michaeljacobdavis/4273026 to your computer and use it in GitHub Desktop.
Save michaeljacobdavis/4273026 to your computer and use it in GitHub Desktop.
inheritsFrom
Function.prototype.inheritsFrom = function (base) {
this.prototype = Object.create(base.prototype);
this.prototype.constructor = this;
this.prototype._super = base.prototype;
return this;
};
var Base = function () {
if (!(this instanceof Base))
throw ('Constructor called without "new"');
};
var Shape = function () {
Base.call(this);
this.sides = 0;
}.inheritsFrom(Base);
Shape.prototype.sharp = function () {
return true;
}
var Square = function () {
Shape.call(this);
this.sides = 4;
}.inheritsFrom(Shape);
Square.prototype.sharp = function () {
return this._super.sharp.call(this);
}
var Circle = function () {
Shape.call(this);
this.radius = 3;
}.inheritsFrom(Shape);
var square = new Square();
console.log(square instanceof Square); // True
console.log(square instanceof Shape); // True
console.log(square.constructor === Square); // True
console.log(square.sides === 4); // True
console.log(square.sharp() === true); //True
var circle = new Circle();
console.log(circle.sides === 0); // True
console.log(circle.radius === 3); // True
Shape.prototype.color = "red";
console.log(circle.color); // Red
console.log(square.color); // Red
Shape(); // Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment