JavaScript:未定义的值赋值

JavaScript: Value assignment to undefined

本文关键字:赋值 未定义 JavaScript      更新时间:2023-09-26

案例1

假设我有:

a = {}
a.x         // would return "undefined"

但是我可以有

b = a.x

控制台将只返回一个undefined

案例2

但是,如果我有:

a           // would throw an error saying "ReferenceError: a is not defined"

我不能有

b = a       // console throws tantrum insisting "ReferenceError: a is not defined"

问题

有什么区别?毕竟两者都是undefined。为什么第一个不抛出错误?

所以为了让自己更清楚:

╭────────────────────┬────────────────────────┬───────────────────────╮
| Resolution         | Property Resolution    | Variable Resolution   |
╞════════════════════╪════════════════════════╪═══════════════════════╡
| Subjective         | Objects                | LexicalEnvironment    |
|────────────────────|────────────────────────|───────────────────────|
| Rule of Procession | Follow Prototype Chain | Follow Scope Chain    |
└────────────────────┴────────────────────────┴───────────────────────┘

感谢@RobG。引用他提供的有用链接:

本规范中使用了两种环境记录值:声明性环境记录和对象环境记录。声明性环境记录用于定义ECMAScript语言语法元素的效果,如FunctionDeclaration、VariableDeclarations和Catch子句,这些子句直接将标识符绑定与ECMAScript语言值相关联。对象环境记录用于定义ECMAScript元素(如Program和WithStatement)的效果,这些元素将标识符绑定与某些对象的属性相关联。