Javascript:为什么关于警报的函数的结果未定义

标签 javascript

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/

相关文章:

javascript - 在 javascript 中访问值

javascript - Gulp 在源文件数组上顺序执行同一任务

javascript - 使用复选框过滤 FullCalendar 事件(使用 javascript 的客户端)

javascript - 限制用户对 Firebase 节点的读/写访问权限不起作用

javascript - Rails 3 - 如何动态创建与参数关联的 html 元素 [ :id]?

javascript - AngularJs 应用程序转到 div 的顶部

javascript - 在 Angular 1.5 组件中使用 ControllerAs

javascript - 单击清除文件上传

javascript - Jquery 与 Asp.net 按钮

javascript - 如何在 React 组件中嵌入和调用外部 JavaScript 函数?