怪异的编程问题
(1)JavaScript中的作用域
var jsFuture = "es6"; (function () { if (!jsFuture) { var jsFuture = "es5"; } console.log(jsFuture); }());
实际输入结果是:es5,而不是es6
原因:变量声明将被提升到最上面.
(2)
var es = []; for (var i = 0; i < 10; i++) { es[i] = function () { console.log("Upcoming edition of ECMAScript is ES" + i); }; } es[6](); // Upcoming edition of ECMAScript is ES10
Notice that, even though var i = 0;
is declared in the for
loop, the scope ofvar i
defaults to global. Hence, when the function es[6]()
is executed, the value of i
is 10
.
(3)