Module und Classes

Geschätzte Lektüre: 9 Minuten 504 Ansichten

Module in JavaScript

Module sind eine Möglichkeit, Code in separate Dateien zu organisieren, um die Wartbarkeit und Wiederverwendbarkeit zu erhöhen. Vor der Einführung von ES6 (ECMAScript 2015) hatte JavaScript kein eingebautes Modulsystem, aber heute gibt es zwei Hauptarten von Modulen:

ES6 Module (Moderne JavaScript Module)

• Exportieren:

// mathUtils.js
export const PI = 3.14159;

export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

// Alternativ: Export am Ende der Datei
// export { PI, add, subtract };

• Importieren:

// app.js
import { PI, add } from './mathUtils.js';

console.log(PI); // 3.14159
console.log(add(5, 3)); // 8

• Standard-Export:

// Calculator.js
export default class Calculator {
  multiply(a, b) {
    return a * b;
  }
}

// app.js
import Calculator from './Calculator.js';
const calc = new Calculator();
console.log(calc.multiply(4, 5)); // 20

CommonJS Module (Node.js Module-System)

• Exportieren:

// mathUtils.js
const PI = 3.14159;

function add(a, b) {
  return a + b;
}

module.exports = {
  PI,
  add
};

// Oder für einzelne Exporte:
// exports.PI = PI;
// exports.add = add;

• Importieren:

// app.js
const math = require('./mathUtils.js');

console.log(math.PI); // 3.14159
console.log(math.add(5, 3)); // 8

Klassen in JavaScript

Klassen in JavaScript sind syntaktischer Zucker über dem bestehenden prototypbasierten Vererbungsmodell von JavaScript. Sie wurden in ES6 eingeführt.

Grundlegende Klassensyntax

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hallo, mein Name ist ${this.name} und ich bin ${this.age} Jahre alt.`);
  }
}

const person1 = new Person('Max', 30);
person1.greet(); // Hallo, mein Name ist Max und ich bin 30 Jahre alt.

Klassen mit Vererbung

class Student extends Person {
  constructor(name, age, studentId) {
    super(name, age); // Aufruf des Eltern-Konstruktors
    this.studentId = studentId;
  }

  study() {
    console.log(`${this.name} mit der Matrikelnummer ${this.studentId} lernt fleißig.`);
  }
}

const student1 = new Student('Anna', 22, '12345');
student1.greet(); // Hallo, mein Name ist Anna und ich bin 22 Jahre alt.
student1.study(); // Anna mit der Matrikelnummer 12345 lernt fleißig.

Statische Methoden und Eigenschaften

class MathUtils {
  static square(x) {
    return x * x;
  }

  static PI = 3.14159;
}

console.log(MathUtils.square(5)); // 25
console.log(MathUtils.PI); // 3.14159

Getter und Setter

class Rectangle {
  constructor(width, height) {
    this._width = width;
    this._height = height;
  }

  get area() {
    return this._width * this._height;
  }

  set width(newWidth) {
    if (newWidth > 0) {
      this._width = newWidth;
    } else {
      console.error('Breite muss positiv sein');
    }
  }
}

const rect = new Rectangle(10, 20);
console.log(rect.area); // 200 (Getter wird aufgerufen)
rect.width = 15; // Setter wird aufgerufen
console.log(rect.area); // 300

Private Felder (ab ES2022)

class BankAccount {
  #balance = 0; // Private Feld

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  getBalance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.getBalance()); // 100
console.log(account.#balance);
// Fehler: Private field '#balance' must be declared in an enclosing class

Kombination von Modulen und Klassen

Ein häufiges Muster ist die Verwendung von Klassen in Modulen:

// shapes.js
export class Circle {
  constructor(radius) {
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius ** 2;
  }
}

export class Square {
  constructor(side) {
    this.side = side;
  }

  area() {
    return this.side ** 2;
  }
}
// app.js
import { Circle, Square } from './shapes.js';

const circle = new Circle(5);
console.log(circle.area()); // ~78.5398

const square = new Square(4);
console.log(square.area()); // 16

Unterschiede zwischen Modulen und Klassen

  • Zweck:
    • Module organisieren Code in logische Einheiten (Dateien)
    • Klassen organisieren Code in Objekte mit Zustand und Verhalten
  • Syntax:
    • Module verwenden import/export
    • Klassen verwenden class, constructor, extends etc.
  • Verwendung:
    • Module werden importiert/exportiert
    • Klassen werden instanziiert (mit new) oder erweitert

Fortgeschrittene Themen

Dynamische Imports

// Dynamischer Import (gibt ein Promise zurück)
import('./mathUtils.js')
  .then(module => {
    console.log(module.add(2, 3));
  })
  .catch(err => {
    console.error('Modul konnte nicht geladen werden', err);
  });

// Oder mit async/await
async function loadModule() {
  const math = await import('./mathUtils.js');
  console.log(math.add(2, 3));
}

Mixins mit Klassen

// Mixin-Funktion
const Serializable = Base => class extends Base {
  serialize() {
    return JSON.stringify(this);
  }
};

class User {
  constructor(name) {
    this.name = name;
  }
}

const SerializableUser = Serializable(User);
const user = new SerializableUser('Max');
console.log(user.serialize()); // {"name":"Max"}

Abstrakte Klassen (Simulation)

class AbstractShape {
  constructor() {
    if (new.target === AbstractShape) {
      throw new Error('AbstractShape kann nicht direkt instanziiert werden');
    }
  }

  area() {
    throw new Error('Methode "area" muss implementiert werden');
  }
}

class ConcreteCircle extends AbstractShape {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius ** 2;
  }
}

// const shape = new AbstractShape(); // Fehler
const circle = new ConcreteCircle(5); // OK

Ausblick

Diese Konzepte bilden die Grundlage für eine strukturierte und wartbare JavaScript-Codebasis. Module helfen bei der Organisation des Codes über mehrere Dateien hinweg, während Klassen eine objektorientierte Programmierung ermöglichen.

Dieses Dokument teilen

Module und Classes

Oder Link kopieren

INHALT

Abonnieren

×
Cancel