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 3 years have passed since last update.

Javascript 備忘録2 <スコープ>

Last updated at Posted at 2021-04-09

■スコープとは
→変数が見える範囲のことをさす

■グローバルスコープ

let a = 0;
let b = 0;

window.c = 0;

上のように指定した場合、グローバルスコープとなる。
→グローバルで宣言した変数は、同じスクリプト内ならどこからでも呼び出すことが可能。

■関数スコープ

function a() {
    let b = 0;
    // このconsole.logは出力される
    console.log(b);
}
// 変数bが宣言されているのは関数a野中なので、関数a野中でのみ使用することができる
console.log(b);

■レキシカルスコープ(外部スコープ)

let a = 2;

function fn1() {
    let b = 3;
    function fn2() {
        let c = 4;
    }
}

→今回のソースコードでは、aはグローバル変数となるのでfn1、fn2からでも呼び出せる
→fn2からみると外部の変数であるa、b
→これはfn2内で呼び出すことが可能である
→このことをレキシカルスコープ(外部スコープ)という

■クロージャー

数字をインクリメントする関数を作りたい


increment();
increment();
increment();

function increment() {
   num = 0;
   num += 1;
   console.log(num);
};

→上のソースコードだと関数increment()が呼ばれるたびに、numは初期化されてしまうので、
コンソールに出力されるのは0のみ

function incrementFactory() {
    num = 0;
    function() increment() {
        num += 1;
    }
    return increment;
}

const increment = incrementFactory();

increment();
increment();
increment();

→まず、incrementFactory()が呼び出されることにより、numが初期化される
→その後、incrementFactory内にある関数incrementが返り値で戻ってくる
→そのため,constで宣言したincrementを呼び出しても、numは初期化されることはなく、インクリメントのみが行われるこになる

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?