Ein Objekt ist eine Sammlung von zusammengehörigen Daten und Funktionen.
const person = {
name: "Anna",
alter: 22,
greet: function() {
console.log("Hallo, ich bin " + this.name);
}
};
console.log(person.name);
console.log(person["alter"]);
Beide Varianten sind gültig.
person.greet();
this verweist auf das aktuelle Objekt.
person.alter = 23;
person.wohnort = "Zürich";
Klassen sind Baupläne für Objekte.
class Person {
constructor(name, alter) {
this.name = name;
this.alter = alter;
}
greet() {
console.log("Hallo, ich bin " + this.name);
}
}
const p1 = new Person("Luca", 19);
const p2 = new Person("Mia", 21);
p1.greet();
p2.greet();
class Auto {
constructor(marke, km) {
this.marke = marke;
this.km = km;
}
fahren(strecke) {
this.km += strecke;
}
}
| Objekt | Konkrete Instanz |
| Klasse | Bauplan |
| Instanz | Objekt aus einer Klasse |