2016-10-22 59 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),因为这样的片段给出了很多输出