2016-10-22 5 views
0

JavaScriptでvaribleの範囲について混乱を感じたので、私は書いた:f();は、私はJavascriptを練習しています

私の意見では
/*the console result*/ 
window 
2 
2 
NaN 

thisポイント:

function f(){ 
     console.log(this);  
     var b=2; 
     console.log(b); 
     this.b++;  
     console.log(b); 
     b++; 
} 
f(); 
console.log(b); 

結果は私を驚か。 bf();のプライベート変数です。 this.b++b++は同じ変数で動作します。

/*the right anwser in my mind*/ 
f 
2 
4 
TypeError 

私が期待した結果を得られなかった理由を説明してください。

+0

'console.log(this.b)'なら 'NaN'なので、' this.b ++ 'は何もインクリメントしません。 – Luke

+0

これは 'window'であり、関数ではありません。変数 'b'は関数内のローカル変数であるためウィンドウスコープには不明です。 –

+2

' this.b'と 'b'は同じ変数ではありません。 –

答えて

-2

4を取得するには、これを行う必要があります this.b = this.b ++; または b = b ++;動作します。

bがそのスコープで定義されていないため、最後の結果としてNanが取得されています。あなたは、詳細についてはjavascriptの変数ホイストについて読むことができます。

3

は、ここで何が起こっているかを打破するのをしてみましょう:

function f(){ 
    /* 
    Since you called this function directly, "this" is pointing 
    to the window object of the browser because it is the global scope 
    */ 
    console.log(this); // window 
    var b=2; // Assigning 2 to a local variable "b" 
    console.log(b); // 2 - because you are logging your local scoped variable 

    /* 
     This is really saying window.b++ and since b isn't typically 
     defined on the window object it is essentially saying: 
     window.b = undefined + 1 
    */ 
    this.b++; 
    console.log(b); // 2 - because you are logging your local scoped variable that hasn't changed 
    b++; // Increment your local scoped variable 
} 

f(); // Calling the function you just defined in the global scope 

/* 
    This is actually logging window.b which is considered to be 
    NaN (not a number) because you incremented "undefined" and 
    since undefined is not a number it can't be incremented 
*/ 
console.log(b); 
+0

私の言葉が不明瞭/混乱している場合は、私に知らせてください。 – rdubya

+0

ありがとうございました。 –

+0

非常に明確に説明してください! –

0

あなたは(var bを使用して)あなたのf関数内のローカル変数にb変数セットを持っているので、あなたがwindow変数を使用してアクセスすることはできません。あなたはthiswindowとして)を使用することができるようになります(外側のスコープでvar bbグローバルに変数を設定した場合

それを行うには:

var b 
 
function f(){ 
 
     // console.log(this); 
 
     b=2; 
 
     console.log(b); 
 
     this.b++;  
 
     console.log(b); 
 
     b++; } 
 
f(); 
 
console.log(b);

最初のconsole.log(this)を無効にしました。そのスニペットが多くの出力を提供するからです。

関連する問題