我有点被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?
发布于 2019-08-23 21:15:44
基本上,当您使用一个还不是Reference error的变量时,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也是object,在您的示例中,您尝试从this访问a的值。
所以看起来
const this = {};
console.log(this.a) // undefinedhttps://stackoverflow.com/questions/57632862
复制相似问题