LoginSignup
0
0

More than 1 year has passed since last update.

【Javascript】closure(クロージャ)について

Last updated at Posted at 2021-06-17

初めに

javascriptのclosure(クロージャ)について学習した内容のoutput用記事です。

※内容に間違いなどがある場合はご指摘をよろしくお願いします。
※こちらの記事はあくまでも個人で学習した内容のoutputとしての記事になります。

前回の記事:
https://qiita.com/redrabbit1104/items/d9e40ccf59f4a6abb1bd

closure(クロージャ)とは

関数の中に関数がある場合、外側の関数で定義した変数や定数を内側で定義した関数が参照する状態のことを言います。この外側に定義されている変数はこの関数の外側からはアクセスできず、内側で定義されている関数でしかアクセスすることができません。このように外側の関数に定義した変数を外側の関数によって閉じ込められていることからclosure(閉められているもの)と呼ばれています。

closureの基本的な形

まずは外側の関数outsideFunction()を用意し、その関数の中にgreetingsという変数を定義します。

function outsideFunction() {
  const greetings = 'hello';
}

このoutsideFunctionの中にさらに関数を定義します。そしてoutsideFunction()の戻り値はこの関数にします。

function outsideFunction() {
  const greetings = 'hello';
  return function () {
    console.log(greetings);
  };
}

外側の関数outsideFunction()を実行し、その結果をinsideFunctionという変数に格納します。insideFunctionにはoutsideFunction()が実行され、return文によってoutsideFunction()の中に定義されている関数(内側の関数)を返します。

//insideFunctionにはoutsideFunction()の戻り値である関数が格納されている
const insideFunction = outsideFunction();     

insideFunctionの中身は以下のようなものになります。

const insideFunction = function () {
    console.log(greetings);
  };

このinsideFunctionを実行してみます。

insideFunction();

するとhelloがコンソールに表示されます。
スクリーンショット 2021-06-15 21.54.19.png
つまりoutsideFunction()の中に宣言した変数greetingsを参照していることになります。
これは普通の関数がglobal scopeの変数greetingを参照するのと同じです。

const greeting = 'hello';
const insideFunction = function () {
  console.log(greetings);
};

この状態を外側の関数outsideFunction()が閉じ込めている状態だといえます。なのでclosureという名前が付けられています。変数greetingsはoutsideFunction()の外側からは変更できません。

function outsideFunction() {
  const greetings = 'hello';
  return function () {
    console.log(greetings);
  };
}

 参考サイト

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