Appearance
Kapitel 9: Objekt-Erweiterungen
9.1 Objekt-Kurzschreibweise (Property Shorthand, Method Shorthand)
📦 Property Shorthand (Eigenschaft-Kurzschreibweise)
Wenn der Variablenname mit dem Eigenschaftsnamen übereinstimmt, kannst du den Namen weglassen.
javascript
const name = "Max";
const alter = 25;
// ❌ Alte Methode (ES5)
var person1 = {
name: name,
alter: alter
};
// ✅ Neue Methode (ES6) - Property Shorthand
const person2 = {
name, // gleich wie: name: name
alter // gleich wie: alter: alter
};
console.log(person2);
// { name: "Max", alter: 25 }📦 Method Shorthand (Methoden-Kurzschreibweise)
Du kannst das Schlüsselwort function und den Doppelpunkt : weglassen.
javascript
// ❌ Alte Methode (ES5)
var person1 = {
name: "Max",
greet: function() {
return "Hallo " + this.name;
}
};
// ✅ Neue Methode (ES6) - Method Shorthand
const person2 = {
name: "Max",
greet() { // kein "function" und kein ":"
return `Hallo ${this.name}`;
}
};
console.log(person2.greet()); // "Hallo Max"🎯 Kombination: Property + Method Shorthand
javascript
const name = "Max";
const alter = 25;
const person = {
name, // Property Shorthand
alter, // Property Shorthand
greet() { // Method Shorthand
return `Hallo, ich bin ${this.name}`;
},
// ... weitere Methoden
};
console.log(person.greet()); // "Hallo, ich bin Max"9.2 Computed Property Names (Berechnete Eigenschaftsnamen)
🧮 Was sind Computed Property Names?
In ES6 können Ausdrücke in eckigen Klammern als Eigenschaftsnamen verwendet werden.
javascript
// ❌ Alte Methode (ES5) - Eigenschaft nachträglich hinzufügen
var key = "dynamicKey";
var obj1 = {};
obj1[key] = "Wert";
console.log(obj1); // { dynamicKey: "Wert" }
// ✅ Neue Methode (ES6) - Computed Property Names
const key = "dynamicKey";
const obj2 = {
[key]: "Wert"
};
console.log(obj2); // { dynamicKey: "Wert" }🎯 Praxisbeispiel: Dynamische Eigenschaftsnamen
javascript
const prefix = "app_";
const id = 123;
const config = {
[`${prefix}${id}`]: "Dies ist eine dynamische Eigenschaft",
[["a", "b", "c"].join("_")]: "A_B_C"
};
console.log(config);
// {
// app_123: "Dies ist eine dynamische Eigenschaft",
// a_b_c: "A_B_C"
// }🎯 Methoden mit Computed Property Names
javascript
const methodName = "greet";
const person = {
name: "Max",
[methodName]() {
return `Hallo, ich bin ${this.name}`;
}
};
console.log(person.greet()); // "Hallo, ich bin Max"9.3 Object.assign() - Objekt-Zusammenführung
📋 Was macht Object.assign()?
Object.assign() kopiert alle enumerable (auflistbaren) Eigenschaften von einem oder mehreren Quell-Objekten in ein Ziel-Objekt.
javascript
// Syntax
Object.assign(target, ...sources)🎯 Einfaches Beispiel
javascript
const target = { a: 1, b: 2 };
const source = { b: 3, c: 4 };
const result = Object.assign(target, source);
console.log(result); // { a: 1, b: 3, c: 4 }
console.log(target); // { a: 1, b: 3, c: 4 } (target wurde verändert!)
console.log(target === result); // trueAchtung: target wird verändert (Mutation)!
🎯 Objekt kopieren (ohne Mutation)
javascript
const original = { a: 1, b: 2 };
// ❌ Falsch - nur Referenz kopieren
const copy1 = original;
copy1.a = 99;
console.log(original.a); // 99 ❌ (Original wurde verändert!)
// ✅ Richtig - echte Kopie mit Object.assign()
const copy2 = Object.assign({}, original);
copy2.a = 99;
console.log(original.a); // 1 ✅ (Original unverändert)🎯 Objekte zusammenführen
javascript
const person = { name: "Max", alter: 25 };
const job = { beruf: "Entwickler", firma: "ABC GmbH" };
// Zusammenführen
const combined = Object.assign({}, person, job);
console.log(combined);
// { name: "Max", alter: 25, beruf: "Entwickler", firma: "ABC GmbH" }🆚 Object.assign() vs Spread-Operator
javascript
const person = { name: "Max", alter: 25 };
const job = { beruf: "Entwickler" };
// Methode 1: Object.assign()
const copy1 = Object.assign({}, person, job);
// Methode 2: Spread-Operator (ES2018+)
const copy2 = { ...person, ...job };
console.log(copy1); // { name: "Max", alter: 25, beruf: "Entwickler" }
console.log(copy2); // { name: "Max", alter: 25, beruf: "Entwickler" }Empfehlung: Verwende den Spread-Operator (lesbarer).
9.4 Objekt-Kurzschreibweise in der Praxis
🎯 Beispiel 1: AJAX-Konfiguration
javascript
function createConfig(url, method, data) {
// ❌ Alte Methode (ES5)
// return {
// url: url,
// method: method,
// data: data
// };
// ✅ Neue Methode (ES6) - Property Shorthand
return {
url,
method,
data
};
}
const config = createConfig("/api/users", "POST", { name: "Max" });
console.log(config);
// { url: "/api/users", method: "POST", data: { name: "Max" } }🎯 Beispiel 2: Modul-Exporte
javascript
// ❌ Alte Methode (ES5)
// module.exports = {
// add: add,
// subtract: subtract,
// multiply: multiply
// };
// ✅ Neue Methode (ES6) - Property Shorthand
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
const multiply = (a, b) => a * b;
module.exports = {
add,
subtract,
multiply
};🎯 Beispiel 3: Event-Handler-Objekt
javascript
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
emit(event, ...args) {
if (this.events[event]) {
this.events[event].forEach(callback => callback(...args));
}
}
}
const emitter = new EventEmitter();
// Method Shorthand beim Event-Handler-Objekt
const handlers = {
onConnect() {
console.log("Verbunden!");
},
onMessage(msg) {
console.log(`Nachricht: ${msg}`);
}
};
emitter.on("connect", handlers.onConnect);
emitter.on("message", handlers.onMessage);9.5 Einführung in Deep Copy (Tiefe Kopie)
⚠️ Shallow Copy vs Deep Copy
javascript
const original = {
a: 1,
b: {
c: 2
}
};
// ❌ Shallow Copy (nur erste Ebene)
const shallowCopy = { ...original };
shallowCopy.b.c = 99;
console.log(original.b.c); // 99 ❌ (verschachteltes Objekt wurde verändert!)
// ✅ Deep Copy (echte Kopie aller Ebenen)
// Methode 1: JSON (einfach, aber hat Einschränkungen)
const deepCopy1 = JSON.parse(JSON.stringify(original));
deepCopy1.b.c = 99;
console.log(original.b.c); // 2 ✅ (Original unverändert)
// Methode 2: Bibliothek verwenden (z.B. lodash)
// import { cloneDeep } from 'lodash';
// const deepCopy2 = cloneDeep(original);🧪 Wann ist eine Deep Copy nötig?
javascript
// Szenario: State-Management in React/Vue
const initialState = {
user: {
name: "Max",
permissions: ["read", "write"]
},
settings: {
theme: "dark"
}
};
// ❌ Falsch - Shallow Copy reicht nicht!
const badUpdate = { ...initialState };
badUpdate.user.permissions.push("admin");
// initialState.user.permissions wurde verändert! ❌
// ✅ Richtig - Deep Copy oder immutable Update
const goodUpdate = {
...initialState,
user: {
...initialState.user,
permissions: [...initialState.user.permissions, "admin"]
}
};
// initialState.user.permissions bleibt unverändert ✅🎉 Zusammenfassung
In diesem Kapitel hast du gelernt:
- ✅ Property Shorthand (
{ name }statt{ name: name }) - ✅ Method Shorthand (
greet() {}stattgreet: function() {}) - ✅ Computed Property Names (
{ [key]: value }) - ✅
Object.assign()für Objekt-Zusammenführung - ✅ Shallow Copy vs Deep Copy (Wann ist eine tiefe Kopie nötig?)
📝 Übung
Property Shorthand:
javascriptconst vorname = "Max"; const alter = 25; // Erstelle ein Objekt mit Property ShorthandMethod Shorthand:
javascript// Erstelle ein Objekt 'calculator' mit den Methoden 'add' und 'subtract'Computed Property Names:
javascriptconst dynamicKey = "status"; // Erstelle ein Objekt mit einem dynamischen SchlüsselObject.assign()vs Spread:javascriptconst obj1 = { a: 1 }; const obj2 = { b: 2 }; // Führe beide Objekte zusammen (zwei Methoden)
➡️ Nächstes Kapitel
In Kapitel 10 lernen wir Set und Map Datenstrukturen - neue Wege, Daten zu speichern und zu verwalten!
