gpt4 book ai didi

javascript - ReferenceError 和 undefined

转载 作者:行者123 更新时间:2023-11-29 10:26:37 24 4
gpt4 key购买 nike

我对这个 js 行为有点困惑。

function foo(){
console.log(a)
}

foo() // ReferenceError: a is not defined

在这种情况下,一切都可以理解。在全局范围内没有定义a,因此我们得到了ReferenceError

现在,这是第二个例子:

function foo(){
console.log(this.a)
}

foo() // undefined

因此,this 指向没有定义a 的全局范围。我们不应该得到相同的 ReferenceError 吗?为什么我们得到 undefined

最佳答案

基本上 引用错误 会在您使用尚未声明 的变量时出现,而 undefined 会在您尝试获取一些变量时出现对象的属性和键不存在于对象中,或者您使变量本身未定义

例如

未定义

  const obj = { };
const array = [];
const newObj = undefined;

console.log(obj.id);// undefined
console.log(newObj);// undefined
console.log(array[0]);// undefined

引用错误

 const obj = { };
console.log(obj[id] = id);

Note this is also an object, In your case you try to access value of a from this

看起来像

const this = {};
console.log(this.a) // undefined

关于javascript - ReferenceError 和 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57632862/

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