formations/javascript/base/exercices/heritage/heritage.js

78 lines
1.5 KiB
JavaScript

/*
* Énoncé:
* Étant donné les classes Shape & Point définies ci dessous, implémenter les sous classes de Shape
* Circle et Polygon et leur méthode getPerimeter respective.
*/
/* Shape */
function Shape() {}
Shape.prototype.getPerimeter = function() {
throw new Error('La méthode getPerimeter doit être implémentée par les sous classes !');
};
/* Point */
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.getDistanceFrom = function(point) {
if( !(point instanceof Point) ) {
throw new Error('L\'argument "point" doit être une instance de Point !');
}
return Math.sqrt( (this.x-point.x)*(this.x-point.x) + (this.y-point.y)*(this.y-point.y));
};
// ---------------------- À compléter -------------------------------
/* Polygon */
function Polygon(p1, p2, p3, p4) {
}
/* Circle */
function Circle(center, radius) {
}
// ------------------------------------------------------------------
/* Tests */
var p1 = new Point(1, 5);
var p2 = new Point(2, 6);
var p3 = new Point(2, -10);
var p4 = new Point(7, -2);
try {
var poly = new Polygon(p1, p2, p3, p4);
console.log( poly instanceof Polygon ); // -> true
console.log( poly instanceof Shape ); // -> true
console.log( poly.getPerimeter() ); // -> 36.06773915172259
} catch(err) {
console.error(err);
}
try {
var c = new Circle(p1, 5);
console.log( c instanceof Circle ); // -> true
console.log( c instanceof Shape ); // -> true
console.log( c.getPerimeter() ); // -> 31.41592653589793
} catch(err) {
console.error(err);
}