gpt4 book ai didi

JavaScript 任何对象的属性都返回 undefined,为什么?

转载 作者:行者123 更新时间:2023-11-30 17:31:12 25 4
gpt4 key购买 nike

我正在研究 JS,想知道为什么任何未定义的 JS 对象属性都返回 undefined

window.myVar // undefined

现在,如果我尝试访问全局属性 myVar(有点像 window.myVar),JS 将抛出错误:

myVar // error: myVar is not defined

注意用

初始化变量
var myVar; // undefined

那么,有人可以解释一下这背后的过程是什么吗?

最佳答案

I am studying JS and was wondering why any not defined JS Object property returned undefined.

Because the specification says so:

  1. Let desc be the result of calling the [[GetProperty]] internal method of O with property name P.

  2. If desc is undefined, return undefined.

虽然全局变量成为全局对象的属性,但尝试解析变量和尝试访问对象的属性是两件不同的事情。

如果您尝试访问 undefined variable ,a reference error is thrown :

  1. If Type(V) is not Reference, return V.

  2. Let base be the result of calling GetBase(V).

  3. If IsUnresolvableReference(V), throw a ReferenceError exception.


关于它真的没什么好说的。之所以这样,是因为语言是这样定义的。如果您要问这背后的原因是什么,那么您必须问问真正从事语言规范工作的人。

关于JavaScript 任何对象的属性都返回 undefined,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23039052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com