问题描述
如果我尝试引用一个不存在的变量,我会在JavaScript中获得ReferenceError。为什么引用不存在的对象属性会返回'undefined'?
以下是一些代码,前提是我在浏览器中编写代码:
If I try to reference a non-existent variable, I get ReferenceError in JavaScript. Why referencing a non-existent object property returns 'undefined'?Here is some code, provided I'm writing it in a browser:
alert(a);
ReferenceError: a is not defined //error is thrown
alert({}.a)
undefined //no error
推荐答案
这就是语言的工作原理。它的基于对象的方法非常灵活,您可以在运行时动态添加,更新和删除对象的属性。访问当前不存在的那个应该产生 undefined
而不是引发异常。例如,这允许检查是否存在并在单个表达式中键入:
That's just how the language works. Its object-based approach is very flexible, and you can dynamically add, update, and remove properties from objects at runtime. Accessing one that is currently not existing should yield undefined
instead of raising an exception. This, for example, allows checking for existence and type in a single expression:
if (prop in obj && typeof obj[prop] == "function") obj[prop]();
// can be written shorter:
if (typeof obj[prop] == "function") obj[prop]();
您可以在不使用它的情况下获取该值。在大多数情况下,使用 undefined
然后会抛出。
You can get the value without using it. Using undefined
then will throw in most circumstances.
相反,变量在其范围内静态声明。访问未声明的变量总是一个错误,合法地抛出 ReferenceError
s。
In contrast, variables are declared statically in their scope. Accessing an undeclared variable is always an error, which legitimates throwing ReferenceError
s.
这篇关于为什么在javascript中引用对象的不存在的属性不会返回引用错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!