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?

【Javascript】クロージャについて【初心者】

Last updated at Posted at 2025-04-09

クロージャとは

  • スコープ内で定義された変数同じスコープ内の関数などで参照できる状態。

なぜクロージャが重要なのか、実際の現場でどんなふうに使えるか

  • スコープ内で変数を定義することで、スコープ外からの不要なアクセスを防ぐことができる。
  • カウンターや在庫管理などをするときに変数の値を保持し続けなければならないときに有効。

クロージャの例

sample.js
const stockManeger = () => {
    const stock = {}
    return {
        add: (merchandise, value) => {
            stock[merchandise] === undefined ? stock[merchandise] = value : stock[merchandise] +=  value;
            console.log(stock);
        },
        remove: (merchandise, value) => {
            if (stock[merchandise] <= value){
                delete stock[merchandise];
                console.log(stock);
            } else if (stock[merchandise] === undefined) {
                console.log(stock);
            } else {
                stock[merchandise] -= value;
                console.log(stock);
            }
        }
    }
}

let operate = stockManeger();
operate.add("banana", 3); //{banana: 3}
operate.remove("banana", 1); //{banana: 2}
operate.add("apple", 2); //{banana: 2, apple: 2}
operate.remove("banana", 2); //{apple: 2}
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?