[JavaScript] Eine Klasse definieren

Klassendefinition ab ES6

// https://javascript.info/class
// https://javascript.info/property-accessors
class Rechteck
{
  // Konstruktor
  constructor(h, b) {
    this.h = h;
    this.b = b;
  }
   
  // public Properties
  get flaeche() {
    return this.Flaeche();
  }
 
  set hoehe(value) {
    this.h = value;
  }
  
  set breite(value) {
    this.b = value;
  }
  
  // public Methoden
  Flaeche() {
    return this.h * this.b;
  }
  
  // statische Methoden
  static Calc(h, b) {
    return h * b;
  }
}
 
const q = new Rechteck(10, 10);
 
console.log(q.flaeche);
q.hoehe = 5;
console.log(q.Flaeche());
console.log(Rechteck.Calc(2, 3));
console.log(Object.getOwnPropertyNames(Rechteck.prototype));

herkömmlich über “function”

function Rechteck(h, b)
{ 
    this.h = h;
    this.b = b;
   
    Rechteck.prototype.Flaeche = function() {
      return this.h * this.b;
    }
}
 
let q = new Rechteck(10, 10);
 
console.log(q.Flaeche());
console.log(Object.getOwnPropertyNames(Rechteck.prototype));