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]クロージャについて[初心者]

Posted at

JavaScriptにおけるクロージャを学んだので備忘録として

クロージャとは

  • 関数とその関数が作成されたスコープの組み合わせを指す
  • クロージャを利用することで関数外部から内部のデータを秘匿できる
  • クロージャ関数が実行された後も関数内のローカルスコープへの参照を保持する

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

  • データをプライベートなデータとして秘匿できる為、外部からの意図しないアクセスをブロックできる
  • ローカルスコープを保持し独立した状態を持つ関数を生成できる為、再利用性が向上する

クロージャの例

sample.js
function countCreator(counter = 0){
  return function(){
    return counter += 1;
  };
};

const countA = countCreator(0); // 0から始まるカウンタ関数
const countB = countCreator(5); // 5から始まるカウンタ関数
const countC = countCreator(); // 実引数がない場合はデフォルト値(0)から始まるカウンタ関数

console.log(countA()) // 1
console.log(countA()) // 2
console.log(countA()) // 3

console.log(countB()) // 6
console.log(countB()) // 7
console.log(countB()) // 8

console.log(countC()) // 1
console.log(countC()) // 2
console.log(countC()) // 3
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?