アロー関数: 簡潔な構文
=> で短く書ける。this の挙動も違う。
アロー関数
=> を使った簡潔な構文。
暗黙の return
波括弧なしで自動 return。
レキシカル this
外側のスコープから継承。
アロー関数
ES6 (ES2015) で導入された、最も重要な構文の一つです。特にコールバック関数(`map` や `setTimeout`)を書く際に圧倒的に便利で、`this` の問題を解決します。ただし、メソッド定義には通常の関数式を使うこともあります。
// 従来の関数function add(a, b) { return a + b;}
// アロー関数const add = (a, b) => a + b;
// 複数行const greet = (name) => { const message = `Hello, ${name}!`; return message;};
// 引数が1つなら括弧省略可const double = x => x * 2;
// オブジェクトを返す(括弧必須)const createUser = (name) => ({ name, age: 0 });Bad
// ❌ Bad: function が冗長const nums = [1, 2, 3];nums.map(function(n) { return n * 2;});Good
// ✅ Good: アロー関数const nums = [1, 2, 3];nums.map(n => n * 2);this の違い
// this の違いconst obj = { name: 'Alice',
// 従来: this はオブジェクトを指す greetTraditional: function() { setTimeout(function() { console.log(this.name); // undefined! }, 100); },
// アロー: this は外側を継承 greetArrow: function() { setTimeout(() => { console.log(this.name); // "Alice" }, 100); }};
// クラスでのメソッドclass Counter { count = 0; // アロー関数プロパティ increment = () => this.count++;} Tip: コールバックにはアロー関数を使う。this の問題を避けられる。
合格ライン
アロー関数を書ける
this の違いを説明できる
演習課題
課題1: アロー関数
通常の関数をアロー関数に変換してください。
課題2: this
アロー関数の this の挙動を確認してください。