Why does referencing undeclared variables throw a reference exception but referencing undeclared properties doesn't?

大兔子大兔子 提交于 2019-12-01 07:14:05

问题


Mozilla says that variables are properties of the global object. If an object has a property that isn't defined, then trying to access it does not create a reference exception - it simply returns that the property is not defined.

If there is such a global object - then why does accessing its properties (ie: variables) that do not exist create reference errors? What is precisely the difference between these two scenarios?

Example:

console.log(x) //x is not declared -> reference error


var x = new Object();
console.log(x.property); //console.log: undefined

回答1:


tl;dr: The way the variable is accessed makes all the difference, not how it is stored.


First some background:

There are basically two ways how variables are "stored".

In a declarative environment, variables are stored in an internal data structure that is not accessible from user code.

In an object environment, variables are stored as properties of a user code accessible object. The global environment happens to be an object environment (it's a bit more complicated than that but lets keep it simple). Therefore global variables are properties of the global object.


So why does accessing a non-existing global variable throw an error? Because it is not relevant how the variables are stored, only how the are accessed.

foo and window.foo are simply two different ways of accessing a global variable.

The language rules for evaluating a variable (foo) explicitly say that if the variable doesn't exist, throw a reference error (again, no matter how it is stored).*

The language rules for evaluating property access (window.foo) say that if the property doesn't exist, undefined should be returned.

And if you think about, this makes much more sense from a consistency perspective. Accessing foo should have the same result, no matter whether the variable is stored in a declarative environment or an object environment.


*: To be more precise: It's the GetValue function that causes the error to be thrown. GetValue is called almost everywhere when resolving a variable (exceptions are typeof and the grouping operator (...)).



来源:https://stackoverflow.com/questions/47066042/why-does-referencing-undeclared-variables-throw-a-reference-exception-but-refere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!