javascript - ReferenceError 和全局对象

标签 javascript window referenceerror global-object

在浏览器的 JavaScript 中,window 是全局对象,这意味着在全局范围内定义的每个变量都是 window 的子对象。那么为什么我会得到这个结果:

console.log(window.foo); // No error, logs "undefined".
console.log(foo);        // Uncaught ReferenceError: foo is not defined.

Fiddle

这两行应该是一样的,不是吗?

最佳答案

因为对于 window.foo,您正在明确地寻找 window 对象的 foo 属性,而在后一个选项中并非如此。在后一个选项中,如果未定义 foo,作为开发人员,您应该能够知道它未定义并获得明确的错误警告,而不是解释器将其设置为 undefined 本身(如第一种情况)会导致意外结果。

Reference Error :

Represents an error when a non-existent variable is referenced. A ReferenceError is thrown when trying to dereference a variable that has not been declared.

查看这篇文章了解更多信息:

引用上面的文章:

A Reference is considered unresolvable if its base value is undefined. Therefore a property reference is unresolvable if the value before the dot is undefined. The following example would throw a ReferenceError but it doesn’t because TypeError gets there first. This is because the base value of a property is subject to CheckObjectCoercible (ECMA 5 9.10 via 11.2.1) which throws a TypeError when trying to convert Undefined type to an Object.

示例:

var foo;
foo.bar; //TypeError (base value, foo, is undefined)
bar.baz; //ReferenceError (bar is unersolvable)
undefined.foo; //TypeError (base value is undefined)

根据定义,既不是属性也不是变量的引用是不可解析的,并且会抛出 ReferenceError,因此:

foo; //ReferenceError

关于javascript - ReferenceError 和全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10102862/

相关文章:

javascript - AngularJS 指令循环遍历数组

javascript - 如何在javascript中检查对象的属性数组是否为空

javascript - 如何使用scrollTo(0,0)打开带有滚动条的Kendo窗口?

window - 如何使QtQuick2.0应用程序窗口不可调整大小?

javascript - 在 Javascript 类中从另一个方法调用一个方法

node.js - '引用错误: _ is not defined ' : error is shown while use LODASH module in node. js,_.isString()

php - 使用 JQuery、AJAX 和 PHP

JavaScript 函数调用上下文

c# - WPF 设计器中窗口上方出现白色边框

node.js - 在 Node.js 中调用导出函数