在浏览器的 JavaScript 中,window
是全局对象,这意味着在全局范围内定义的每个变量都是 window
的子对象。那么为什么我会得到这个结果:
console.log(window.foo); // No error, logs "undefined".
console.log(foo); // Uncaught ReferenceError: foo is not defined.
这两行应该是一样的,不是吗?
最佳答案
因为对于 window.foo
,您正在明确地寻找 window
对象的 foo
属性,而在后一个选项中并非如此。在后一个选项中,如果未定义 foo
,作为开发人员,您应该能够知道它未定义并获得明确的错误警告,而不是解释器将其设置为 undefined
本身(如第一种情况)会导致意外结果。
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/