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.

【JavaScript】クロージャとは?

Posted at

はじめに

LeetCodeの「30Days of JavaScript」の第二問「2620.Counter」を解いています。

この中で「クロージャ(Closure)」という概念が登場しますが、初見だったので簡単に性質をまとめます。

誤りや補足事項があればぜひ教えてください!!

クロージャ(Closure)とは?

そもそもJavaScriptにおいて、関数は同じスコープ内外の全ての変数に対してアクセスできます。

このスコープは、関数の「レキシカル環境(lexical environment)」と呼ばれます。

そして、関数とこのレキシカル環境の組み合わせのことを「クロージャ(closure)」といいます。

クロージャの具体例

JavaScriptでは、関数内に関数を宣言し、それをreturnすることができます。

関数内の関数は、これより上で宣言されたすべての変数に対してアクセスできます。

function createAdder(a) {
  return function add(b) {
    const sum = a + b;
    return sum;
  }
}
const addTo2 = createAdder(2);
addTo2(5); // 7

上の例において、内部の関数のadd()は変数aにアクセスできます。

これがクロージャの性質です。

所感・疑問など

  • レキシカル環境とは?
  • クロージャのありがたみがイマイチわからない

参考・引用

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?