弄糊涂了。
var message = "Xinrui Ma";
var call = (function(){
message = "I am cool";
})();
alert(message);在我看来,代码将被这样对待:
var message = "Xinrui Ma";
var call = (function(){
var message; // it will add message declaration here
message = "I am cool";
})();
alert(message); // this should alert the "Xinrui Ma", not the "I am cool",
// cause Hoisting is JavaScript's default behavior of moving all declarations
// to the top of the current scope 但事实上,它输出了“我很酷”,为什么?
发布于 2014-09-10 17:49:17
如果在函数中没有变量声明,它将使用包含范围中的变量。它不会创建一个新的局部变量--如果这样做,就不会有任何方法来引用闭包变量。
这与提升无关,只有在声明函数中的变量时才会发生这种情况。如果你写道:
var call = (function() {
message = "I am cool";
var message;
})();在这种情况下,var声明将被悬挂到函数的顶部。
发布于 2017-03-11 18:13:23
var关键字用于创建本地作用域,默认情况下它使用全局范围。因此,这里的消息指向全局范围,您正在修改它。
你可以防止
var message = "Xinrui Ma";
var call = (function(){
var message = "I am cool";
})();
alert(message);https://stackoverflow.com/questions/25771837
复制相似问题