2016-10-22 87 views
0

我練的Javascript的範圍,所以我寫了:我感到困惑,在JavaScript中varible

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

,結果讓我大吃一驚:

/*the console result*/ 
window 
2 
2 
NaN 

在我看來,thisf();bf();的私有變量。 this.b++b++對相同的變量進行操作。

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

請解釋爲什麼我沒有得到預期的結果。

+0

如果'console.log(this.b)'是'NaN',那麼'this.b ++'不會增加任何內容。 – Luke

+0

這是'窗口'而不是函數。所以變量'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

你有b變量設置爲局部變量在f功能(使用var b),所以你不能使用window變量訪問。

如果設置(在外部範圍的var b)的b可變全球,你將能夠使用this(如window)做到這一點:

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),因爲這樣的片段給出了很多輸出