Advertisement
dabidabidesh

ClassHierarchy

Feb 15th, 2021
2,898
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //jsa2/19 PROTOTYPES AND INHERITANCE/05ClassHierarchy.js
  2. const figures = () => {
  3.   class Figure {
  4.     constructor(units) {
  5.       if (!units) units = 'cm';
  6.       this.units = units;
  7.       if (new.target === Figure) {
  8.         throw new TypeError('Figure class is abstract');
  9.       }
  10.     }
  11.     changeUnits(value) {
  12.       this.units = value;
  13.     }
  14.     scaleParam(param) {
  15.       const values = { mm: 1, cm: 10, m: 1000 };
  16.       return (values.cm * param) / values[this.units];
  17.     }
  18.     toString() {
  19.       return `Figures units: ${this.units}`;
  20.     }
  21.   }
  22.   class Circle extends Figure {
  23.     constructor(radius, units) {
  24.       super(units);
  25.       this._radius = radius;
  26.     }
  27.     get area() {
  28.       return Math.PI * this.radius * this.radius;
  29.     }
  30.     get radius() {
  31.       return this.scaleParam(this._radius);
  32.     }
  33.     toString() {
  34.       return `${super.toString()} Area: ${this.area} - radius: ${this.radius}`;
  35.     }
  36.   }
  37.   class Rectangle extends Figure {
  38.     constructor(width, height, units) {
  39.       super(units);
  40.       this._width = width;
  41.       this._height = height;
  42.     }
  43.     get area() {
  44.       return this.width * this.height;
  45.     }
  46.     get width() {
  47.       return this.scaleParam(this._width);
  48.     }
  49.     get height() {
  50.       return this.scaleParam(this._height);
  51.     }
  52.     toString() {
  53.       return `${super.toString()} Area: ${this.area} - width: ${this.width
  54.         }, height: ${this.height}`;
  55.     }
  56.   }
  57.   return { Figure, Circle, Rectangle };
  58. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement