はじめに
こんにちは!@70days_jsです。
Closureを学びました。
60日目。(2019/12/17)
よろしくお願いします。
サイトURL
やったこと
結論から。
Closureとは?
変数が定義された環境を保持する仕組み
という解釈が一番しっくりきました。
間違っていたらコメントよろしくお願いします。
とてもシンプルなカウンターを作りました。(gif)↓
html↓
<body>
<h1>Closure</h1>
<input type="button" id="button" value="+" />
<input type="button" id="button2" value="-" />
<div id="displalyCount"></div>
</body>
JavaScript↓
function countApp() {
let count = 0;
return function plusCount() {
count++;
return count;
};
}
function countApp2() {
let count = 0;
return function plusCount() {
count--;
return count;
};
}
let button = document.getElementById("button");
let button2 = document.getElementById("button2");
let displalyCount = document.getElementById("displalyCount");
let counter1 = countApp();
let displalyCount2 = document.getElementById("displalyCount2");
let counter2 = countApp2();
button.addEventListener("click", function() {
counter1();
displalyCount.innerHTML = counter1() + counter2();
});
button2.addEventListener("click", function() {
counter2();
displalyCount.innerHTML = counter1() + counter2();
});
countApp関数のなかのcountは常に保存された状態です。
function countApp() {
let count = 0;
return function plusCount() {
count++;
return count;
};
}
なので、この先countApp関数を使おうと思えば、
let hoge = countApp();
のようにしてhogeを経由すれば、先に行っていたカウントは消されずに済みます。
今回、押した回数の数え方はここで行っています。
counter1();
displalyCount.innerHTML = counter1() + counter2();counter2();
displalyCount.innerHTML = counter1() + counter2();
感想
Closureは分かったような、まだ分かり切れていないような。。。
何だろう。わかってるのだろうか・・・?
最後まで読んでいただきありがとうございます。明日も投稿しますのでよろしくお願いします。
参考
- JavaScript中級者への道【5. コールバック関数】 ブレイクスルーJavaScript フロントエンドエンジニアとして越えるべき5つの壁―オブジェクト指向からシングルページアプリケーションまで(← 本を借りました。リンクはamazonページです)