Dieses Kapitel listet einige Ideen zum ES6-Codierungsstil auf
var versus let versus const (Details sind im Kapitel über Variablen erklärt)
const. Du kannst sie für alle Variablen verwenden, deren Werte sich nie ändern.let – für Variablen, deren Werte sich ändern.var. readFilePromisified(filename)
.then(text => console.log(text))
Für mehrzeilige Funktionen eignen sich auch herkömmliche Funktionen (mit der Einschränkung, dass this nicht lexikalisch ist)
readFilePromisified(filename)
.then(function (text) {
const obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
});
Einzeilige Funktionen sind oft wegwerfbar. Wenn eine Funktion nicht so ist, hat eine herkömmliche Funktion den Vorteil, dass du ihr einen Namen geben kannst, was für Dokumentation und Fehlersuche nützlich ist.
}, const obj = {
foo() {
},
bar() {
},
};
// Generator function declaration
function* genFunc() { ··· }
// Generator function expression
const genFunc = function* () { ··· };
// Generator method definition in an object literal
const obj = {
* generatorMethod() {
···
}
};
// Generator method definition in a class definition
class MyClass {
* generatorMethod() {
···
}
}
Details sind im Kapitel über Generatoren erklärt.
// Mark optional parameters via the parameter default value `undefined`
function foo(optional = undefined) { ··· }
// Mark required parameters via a function that throws an exception
function foo(required = throwException()) { ··· }
// Enforcing a maximum arity (variant 1 of 2)
function f(x, y, ...empty) { // max arity: 2
if (empty.length > 0) {
throw new Error();
}
}
// Enforcing a maximum arity (variant 2 of 2)
function f(x, y) { // max arity: 2
if (arguments.length > 2) {
throw new Error();
}
}
Zusätzlich sind die ES5-Codierungsstil-Tipps in „Speaking JavaScript“ für ES6 immer noch relevant.