var name="Jim";
var func=function(){
alert(name);
var name=true;
}
func();
var name="Jim";
var func=function(){
alert(name);
name=true;
}
func();
两个函数有不同的结果,谁能给我解释一下?
最佳答案
发生这种情况的原因来自hoisting .函数范围内的变量声明被提升到顶部。这意味着您的第一个函数实际上看起来像这样
var name="Jim";
var func=function(){
var name;
alert(name);
name=true;
}
func();
这应该更清楚为什么警告 undefined。
参见 "var hoisting"以获得更深入的解释。
Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.
关于Javascript:为什么关于警报的函数的结果未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32570772/