ES2015(ES6)に関する私的メモ
const, letについて
・従来からある何もない変数やvarとの比較をすると、スコープと再代入・再宣言可能かどうかで違いがあります。
function hello(){ { a = "none"; var b = "var"; let c = "let"; const d = "const"; } console.log(b); // var try{ console.log(c); }catch(e){ console.log(e); // Uncaught ReferenceError: c is not defined } try{ console.log(d); }catch(e){ console.log(e); // Uncaught ReferenceError: d is not defined } } hello(); console.log(a); // none
分割代入
配列から値を抜き出して、別の変数に入れます。
const [a,b,c] = ["one", "two", "three"]; console.log(a); // one console.log(b); // two console.log(c); // three
■参考リンク
分割代入
アロー関数
従来の関数式の省略構文だが、従来の関数と違う部分もある。
従来の関数
function add(a, b){ return a + b; } function greeting(name){ return "Hello" + name + "!"; }
アロー関数
let add = (a,b) => { return a + b; } // 中括弧を削除するとreturnを省略可能 add = (a,b) => a + b; // アロー関数内が複数行になる場合は、中括弧をつけて、returnを書く add = (a,b) => { let c = 10; return a + b + c; } // 引数が1つであれば、引数部分の括弧を省略可能。 // 逆に、引数がなかったり、複数あった場合は、()で括らないといけない。 let greeting = name => "Hello" + name + "!";
オブジェクトリテラルを返したい場合は、括弧をつけること
let obj = name => ({name: name});
thisが何を指すのかが違う
var obj = { allow_function: () => console.log(this), traditional_function: function(){ console.log(this) } } obj.allow_function(); // thisはグローバルを指す(アロー関数自身はthisを持たない) obj.traditional_function(); // thisは変数obj自体を指す。
■参考リンク
アロー関数式