ReferenceError和全局对象 [英] ReferenceError and the global object

查看:174
本文介绍了ReferenceError和全局对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javascript 窗口是全局对象,这意味着全局范围内的每个对象都是<的子对象code>窗口。那么为什么我得到这个结果:

In javascript window is the global object, which means every object in the global scope is a child of window. So why I get this result:

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

小提琴

这两行应该相同,不应该吗?

Those two lines should be the same, shouldn't they?

推荐答案

因为使用 window.foo ,您明确要查找 foo 属性 window 对象在后一个选项中不是这种情况。在后一个选项中,如果未定义 foo ,您应该作为开发人员知道它未定义并获得明确的错误警告而不是解释器设置它单独 undefined (如第一种情况),这将导致意外的结果。

Because with window.foo you are explicitly looking for foo property of window object which is not the case in latter option. In the latter option, if foo isn't defined, you should as developer be able to know that it isn't defined and get the clear error warning rather than interpreter setting it to undefined on its own (like first case) which will lead to unexpected results.

参考错误

Reference Error:


表示引用不存在的变量时的错误。
尝试取消引用尚未声明的变量时抛出ReferenceError。

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.

看一下这篇文章更多信息:

Take a look at this article for more info:

  • Understanding JavaScript’s ‘undefined’

从上面的文章引用:


如果基准值未定义,则参考被视为无法解析。因此,如果未定义点之前的值,则属性引用是不可解析的。下面的示例将抛出一个ReferenceError,但它不会,因为TypeError首先到达那里。这是因为属性的基值受CheckObjectCoercible(ECMA 5 9.10到11.2.1)的影响,在尝试将Undefined类型转换为Object时抛出TypeError。

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

这篇关于ReferenceError和全局对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆