0
0

More than 3 years have passed since last update.

年末まで毎日webサイトを作り続ける大学生 〜60日目 Closureを学ぶ〜

Posted at

はじめに

こんにちは!@70days_jsです。

Closureを学びました。

60日目。(2019/12/17)
よろしくお願いします。

サイトURL

やったこと

結論から。
Closureとは?
変数が定義された環境を保持する仕組み
という解釈が一番しっくりきました。

間違っていたらコメントよろしくお願いします。

とてもシンプルなカウンターを作りました。(gif)↓

test3.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は分かったような、まだ分かり切れていないような。。。
何だろう。わかってるのだろうか・・・?

最後まで読んでいただきありがとうございます。明日も投稿しますのでよろしくお願いします。

参考

  1. JavaScript中級者への道【5. コールバック関数】 ブレイクスルーJavaScript フロントエンドエンジニアとして越えるべき5つの壁―オブジェクト指向からシングルページアプリケーションまで(← 本を借りました。リンクはamazonページです)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0