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 1 year has passed since last update.

クロージャーについて

Posted at

クロージャーとは

クロージャーとは関数とその関数が宣言された時の
外側にあった環境を合わせて指す用語のこと。

関数とその関数スコープ内にある変数をまとめて指し、
セットで保存される現象そのものの事

なぜクロージャーが重要なのか

チームでコーディングをしていくとコード量が増えるため、
自分のプログラムで使用しているオブジェクトの変数の値などが他のプログラムで
容易に書き換え得てしまうと予期せぬエラーに繋がる恐れがある。
そのため、クロージャーを使う事で外部から変数へのアクセスを
防止する為の役割も担っている。

実際の現場でどのように使えるのか

以下の ◆クロージャーの例 のように
ベースとなる関数を作成し、コードのバリエーションを増やす事が容易。

◆クロージャーの例

js
function makeAdder(x) {
  return function (y) {
    return x + y;
  };
}

const add5 = makeAdder(5);
const add10 = makeAdder(10);

console.log(add5(2)); // 7
console.log(add10(2)); // 12

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?