OO - Native Inheritance
by Joshua McNeese
JavaScript
// our "parent" object
var Shape = function() {
// convert passed in arguments to an array of sides
this.sides = Array.prototype.slice.apply(arguments);
};
// our "child" object"
var Square = function(a, b, c, d) {
// call our parent's constructor
Shape.call(this, a, b, c, d);
};
Square.prototype = Object.create(Shape.prototype);
Square.prototype.area = function() {
return this.sides[0] * this.sides[1];
};
var sq1 = new Square(4, 4, 4, 4);
console.log(sq1.area());
var Circle = function(circumference) {
Shape.call(this, circumference);
this.diameter = circumference / Math.PI;
this.radius = this.diameter / 2;
};
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.area = function() {
return Math.pow(this.radius, 2) * Math.PI;
};
var circle1 = new Circle(16);
console.log(circle1.area());
var Triangle = function(a, b, c) {
Shape.call(this, a, b, c);
this.halfPerimeter = (a + b + c) / 2;
};
Triangle.prototype = Object.create(Shape.prototype);
Triangle.prototype.area = function() {
// heron's forumula
return Math.sqrt(
this.halfPerimeter *
(this.halfPerimeter - this.sides[0]) *
(this.halfPerimeter - this.sides[1]) *
(this.halfPerimeter - this.sides[2])
);
};
var triangle1 = new Triangle(24, 24, 24);
console.log(triangle1.area());