クロージャ
closure, 関数閉包
関数とその関数が作られた時の環境(スコープ)のペア
文脈により様々指す
環境とセットで保持しておける仕組み
返されるオブジェクト
返されるオブジェクト内の個々の関数
この書き方のパターン
code:js
function closure() {
let x = 1;
return {
get: () => x,
set: (val) => x = val
};
}
const obj = closure();
obj.get(); // 1
obj.set(10);
obj.get(); // 10
通常、関数が終了したら中の変数は消えるはずだが、クロージャにより生き続ける
メリット
完全なprivate変数を実現できる
xには外からアクセスできない
クラスと比較して
thisやnewキーワードが不要
thisの文脈による変化がない
複数のクロージャ
code:js
function createBankAccount(initial) {
let balance = initial;
return {
deposit: (amount) => {
balance += amount;
return balance;
},
withdraw: (amount) => {
balance -= amount;
return balance;
},
check: () => balance
};
}
const myAccount = createBankAccount(1000);
myAccount.deposit(500); // 1500
myAccount.withdraw(200); // 1300
myAccount.check(); // 1300
const yourAccount = createBankAccount(1000);
yourAccount.check(); // 1000 (独立している!)
イベントハンドラ
code:js
function setupButton(buttonId, message) {
let clickCount = 0;
document.getElementById(buttonId).onclick = () => {
clickCount++;
console.log(${message}: ${clickCount}回目);
};
}
高階関数
code:js
const multiply = x => y => x * y;
const double = multiply(2); // 2を記憶
const triple = multiply(3); // 3を記憶
double(10); // 20
triple(10); // 30
Claude.icon