LoginSignup
4
4

More than 5 years have passed since last update.

JavaScript の変数スコープで嵌る 1

Last updated at Posted at 2013-09-11

問題

(function (a) {
  console.log("outer:" + a);
  (function () {
    console.log("inner:" + a);
    var a = "piyo";
  })();
})("hoge");

↓下と同義

(function (a) {
  console.log("outer:" + a);
  (function () {
    var a;
    console.log("inner:" + a);
    a = "piyo";
  })();
})("hoge");

結果 (出力)

outer: hoge
inner: undefined

結論

var キーワードを使い変数を宣言すると、その変数名では上位のスコープが参照されなくなるため、値が代入される前に参照すると undefined が返る。

ちなみに… var キーワードを取り払うと結果は次のようになる。

outer: hoge
inner: hoge

同じ変数名を使いまわす時は要注意。
変数はスコープの上の方で宣言しよう。

4
4
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
4
4