有人可以解释这个小提琴的输出吗?

时间:2014-09-24 06:50:14

标签: javascript web concept

我有这个代码。我已经写了' 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 个答案:

答案 0 :(得分: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();