2014-09-24 61 views
1

我有这段代码。我已经写了'i'(评论中)的价值,我认为这是正确的产出。但是输出/警报是不同的。有人可以解释这个小提琴的输出吗?

小提琴:http://jsfiddle.net/e2jbno4a/
代码:

var i = 10; 

function outer() { 
    alert(i); // 10 
    var i = 5; 
    alert(i); // 5 
    function inner() { 
     var i = 20; 
    } 
    inner(); 
    alert(i); // 5 
    if (1) { 
     var i = 30; 
    } 
    alert(i); // 5 
    setTimout(function() { 
     alert(i); // 5 
    }, 100); 
} 

outer(); 

有人可以让我知道了输出的原因是什么?或者只是解释具体概念的指针?

+1

http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript加HTTP:// javascriptissexy。 com/javascript-variable-scope-and-hoisting-explained/ – Cheery 2014-09-24 06:54:27

+0

概念是“词法范围”和“提升” – elclanrs 2014-09-24 06:55:15

回答

1

所以,一步一步:

var i = 10; 

function outer() { 
    alert(i); // undefined 
    var i = 5; 
    alert(i); // 5 (i now references the `i` in this function's scope.) 
    function inner() { 
     var i = 20; // (The `20` is only available in the scope of `inner`) 
    } 
    inner(); 
    alert(i); // 5 (So, this `i` still references the `var i = 5;` one) 
    if (1) { 
     var i = 30; 
    } 
    alert(i); // 30 (This one actually alerts `30`. There is no block scope in JS) 
    setTimeout(function() { 
     alert(i); // 5 (This will log `30`, you made a typo in the `setTimeout` call) 
    }, 100); 
} 

outer(); 
+0

答案是错误的。第一个输出未定义。参见上面标记的重复问题的例子'8'。 – halkujabra 2014-11-08 02:54:05

+0

修正了@halkujabra。 – Cerbrus 2014-11-08 07:12:37

相关问题