Skip to content

Instantly share code, notes, and snippets.

@tenorok
Created November 16, 2013 14:02
Show Gist options
  • Save tenorok/7500451 to your computer and use it in GitHub Desktop.
Save tenorok/7500451 to your computer and use it in GitHub Desktop.
JavaScript: Extends
/* Base class */
function Shape() {
this.area = function() { throw 'Abstract method'; };
}
/* Extends Shape */
function Rectangle(width, height) {
var parent = new Shape();
for(var p in parent) this[p] = parent[p];
this.width = width;
this.height = height;
var _privateMethod = function() {
return 'Private string. Width = ' + this.width;
}.bind(this);
this.publicMethod = function() {
return _privateMethod();
};
this.area = function() {
return this.width * this.height;
};
}
/* Extends Rectangle */
function Square(side) {
var parent = new Rectangle(side, side);
for(var p in parent) this[p] = parent[p];
this.side = side;
this.area = function() {
return this.side * this.side;
};
this.hypotenuse = function() {
return Math.sqrt(this.area() + this.area());
}
}
var square = new Square(100);
console.log(square.hypotenuse());
console.log(square instanceof Square); // true
console.log(square instanceof Rectangle); // false
console.log(square.publicMethod()); // Private string. Width = 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment