2017-09-17 1 views
2

これらの2つの例の間には、微妙な違いがありますが、違いがありますか?for-loopの最初のステートメントで宣言された変数は、スコープされているか特別に扱われていますか?

for (var foo = 0; …; …) 
    statement; 

var foo = 0; 
for (; …; …) 
    statement; 

私はそれが微妙に異なって動作しますが、私の知る限り、fooはまだ機能スコープの両方のケースであることを読んだいくつかのコメントを覚えているようです。違いは何ですか?

(私はECMA-262 13.7.4を読みしようとしたが、それは私の頭の上のビットになってしまった。)

+1

'foo':

console.log(foo); // undefined value but doesn't throw an error var foo = "Hello, world!";

それと等価ですどちらの場合でもまだ関数スコープですが、それは正しい。 – Tomalak

答えて

3

はい、違いがあります。変数が宣言されていない場合は

1-

var foo;        // hoist foo (declare it at top) 
for (foo = something; …; …)   // but doesn't assign the value at top, it will assign it where it was before the hoisting 
    statement; 

ではなく、に相当:

var foo = something;     // wrong assumption: it should not move the assignemet to top too, it should move just the declaration 
for (; …; …) 
    statement; 

証明

for (var foo = something; …; …) 
    statement; 

は同等ですエラーがスローされます。

console.log(foo);

2-変数に値が代入されることはありません場合は、その値がundefinedです:

var foo; 
 

 
console.log(foo);

3-割り当てトップに宣言(ホイスト)を移動ではなく:

var foo; // declared first so it doesn't throw an error in the next line 
 

 
console.log(foo); // undefined so the assignment is still after this line (still at the same place before hoisting) 
 

 
var foo = "Hello, world!"; // assignment here to justify the logged undefined value

+0

あなたは最後の2つがどう違うかを詳しく説明できますか? – Tomalak

+0

私はまだ3番目の例がどのように "間違っている"かは分かりません。それは間違いではなく、同じことを書く別の方法です。 – Tomalak

+0

@Tomalak私は間違った仮定**を意味しました**:誰かが間違った想定をしていると思うのは間違っています。私はコメントを言い直します。 –

関連する問題