0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

クロージャについて

0
Posted at

#クロージャとは

関数とその関数が宣言された時の外側にあった環境(変数など)を合わせて指す用語です。
下の例では、numAの値は、返り値である関数の中に同封(enclosed) →  クロージャ されます。

function add(numA) {
  return (numB) => numA + numB;

#なぜクロージャが重要なのか、どんな時に活用できるのか

クロージャを活用すると、変数の値を維持することができるプライベート変数を作成することができ、外部から変数を参照することはできなくなります。
グローバルスコープにある変数だと、変数が意図せず変更されないか気を使わないといけないですよね。

#クロージャの例

const countUp = () => {
  let count = 0;
  return {
    addOne: () => {
      count++;
    },
    show: () => {
      console.log(count);
    }
  };

})();

countUp.show(); // 0

countUp.addOne();
countUp.show(); // 1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?