首页 > 解决方案 > javascript中未定义街道错误

问题描述

我是 Javascript 的初学者,我有以下代码:

let address = {
  street: 'Brighton',
  city: 'NY',
  zipcode: 121212,

  showAddress() {
    console.log(street + ' ' + city + ' ' + zipcode);// here is the issue I cannot understand why
  }
}

let address1 = address.showAddress(); 

上面的代码显示错误

未捕获的 ReferenceError:街道未在 Object.showAddress 中定义

标签: javascript

解决方案


在上面,{}作为对象文字而不是块。没有在 .street范围内命名的变量showAddress()

您可以使用this它将引用父对象来访问它。根据MDN

当一个函数作为对象的方法被调用时,它的 this 被设置为调用该方法的对象

let address = {
  street: 'Brighton',
  city: 'NY',
  zipcode: 121212,

  showAddress() {
    console.log(this.street + ' ' + this.city + ' ' + this.zipcode);// here is the issue I cannot understand why
  }
}

let address1 = address.showAddress(); 


推荐阅读