自分用ES6まとめ
(2018/08/18) 情報が古いけど、消すのもアレなので置いておきます..
そのうち内容増やす
実行環境について
- babelでES5のコードに直して使うと良い感じ
- Node.jsで動かす場合はbabel-nodeが便利
全般
- 関数の引数にデフォルト値が簡単に設定できるようになった
アロー関数式
- 無名関数を短く書ける
- 式が一つだけの場合は
return
と{ }
を省略できる - 引数が1つだけ、且つデフォルト値が無い場合には
( )
を省略できる - function構文と違い、
this
は関数外のthis
をそのまま指す
JavaScript
// 通常
var hoge = (foo) => { return foo + "bar" };
// 式が一つの場合
var fuga = foo => foo + "bar";
クラス構文
- C#とかJavaのクラスみたいに書ける。
- 飽くまでfunctionを利用したシンタックスシュガー。
- 継承も出来る
JavaScript
class Foo extends Base {
constructor(foo = "defaultValue") {
super(foo);
}
bar() {
console.log("bar");
}
static piyo() {
console.log("piyo");
}
}
importとexport - モジュール構文
classes.js
export default class Main {
say() { console.log("MainClass"); }
}
export class Sub {
say() { console.log("SubClass"); }
}
export class Sub2 {
say() { console.log("SubClass2"); }
}
main.js
import Main, { Sub, Sub2 as newName } from "./classes";
new Main().say(); // => MainClass
new Sub().say(); // => SubClass
new newName().say(); // => SubClass2
エクスポートしたいクラスや変数をexport default
とすると、メインの内容としてエクスポート出来る。
その場合、インポートでメインの内容は{ }
の外にある必要がある。