この章では、ES6 コーディングスタイルに関連するいくつかのアイデアについて説明します。
var、let、const の使い分け (詳細は 変数の章 で説明しています)
const を優先します。値が決して変わらないすべての変数に使用できます。let を使用します。var は使用しないでください。 readFilePromisified(filename)
.then(text => console.log(text))
複数行の関数の場合、従来の関数も適切に動作します (this がレキシカルではないという注意点がありますが)。
readFilePromisified(filename)
.then(function (text) {
const obj = JSON.parse(text);
console.log(JSON.stringify(obj, null, 4));
});
単一行の関数は使い捨てになる傾向があります。関数が使い捨てではない場合、従来の関数には名前を付けられるという利点があり、ドキュメント作成やデバッグに役立ちます。
}, で終わります。 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() {
···
}
}
詳細は ジェネレーターの章 で説明しています。
// 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();
}
}
さらに、「Speaking JavaScript」の ES5 コーディングスタイルのヒント は ES6 にも関連しています。