setup()
の設計は クロージャの考え方そのものconst x = 10; // ← これは「グローバル(このファイルの外でも見える)」変数
function showX() {
console.log(x); // ← ここからも見える
}
function example() {
const y = 5; // ← y は example の中でしか使えない
console.log(y);
}
console.log(y); // ❌ エラー! y はここでは見えない
変数の置き場所 | どこから見える? |
---|---|
外で定義 (const x = ... ) |
どこからでも見える |
関数の中で定義 (const y = ... ) |
その関数の中だけ |
function counter() {
let count = 0; // ← count はこの中だけの変数
return () => { // ← 無名関数(アロー関数)
count += 1;
console.log(count);
};
}
const myCounter = counter(); // counter() を呼ぶと関数が返ってくる
myCounter(); // 1
myCounter(); // 2 ← count を覚えてる!
🎯 count は本来 counter() の中の変数
→ でも
myCounter
がそれを「覚えている」→ これが クロージャ(closure)。