Can someone explain the output of this fiddle?
本问题已经有最佳答案,请猛点这里访问。
我有这个密码。我已经写了"i"(在注释中)的值,我期望它是正确的输出。但是输出/警报是不同的。
小提琴:http://jsfiddle.net/e2jbno4a/代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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(); |