Javascript 全局引用错误

标签 javascript window global-variables hoisting

<分区>

我在面试中遇到了这个问题,我很好奇为什么这两个输出不同的东西:

(function() {
    console.log(bar);
    console.log(baz);
    foo();

    function foo() {
        console.log('aloha');
    }

    var bar = 2;
    baz = 3;
})();

输出:

undefined
Uncaught ReferenceError: baz is not defined 

鉴于:

(function() {
    console.log(bar);
    console.log(window.baz);
    foo();

    function foo() {
        console.log('aloha');
    }

    var bar = 2;
    baz = 3;
})();

输出:

undefined
undefined
'aloha'

bazwindow.baz 的引用方式有何不同?我虽然全局变量自动附加到窗口?

最佳答案

A ReferenceError indicates that an invalid reference value has been detected (ECMA 5 15.11.6.3)

In practical terms, this means a ReferenceError will be thrown when JavaScript attempts to get the value of an unresolvable reference. (There are other cases where a ReferenceError will be thrown, most notably when running in ECMA 5 Strict mode. If you’re interested check the reading list at the end of this article)

要进一步阅读,请查看 here .

关于Javascript 全局引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22244387/

相关文章:

javascript - 在 'option' 内嵌套数据列表 'div' 显示 "Element ' 选项'不能嵌套在元素 'div' 内“

javascript - 我必须做什么才能规避 JSON 的 JavaScript 同源策略...这也适用于 XML 数据吗?

iPhone 正确的横向窗口坐标

c# - 禁用 wpf 窗口中的最大化容量

java - 如何在用户不看到它的情况下打开它?

javascript - javascript中的变量范围

javascript - 在 Visual Studio 2017 中保存或发布时,Typescript 无法编译

javascript - CSS 饼图切片无法悬停

javascript - 全局变量在开关内不起作用 - javascript

c++ - 全局 const 变量定义 - 在 C++ 中通过 extern 访问