javascript - 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 中定义
解决方案
在上面,{}
作为对象文字而不是块。没有在 .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();
推荐阅读
- c# - 将多个 SQL 文件合并为一个 SQL 文件
- kubernetes - Kubernetes:通过 WebSocket API 执行;关闭标准输入?
- c++ - C ++从任何字符串中选择某些字符集
- amazon-web-services - 将数据从 MariaDB RDS 表导出到 S3 - 数据管道失败
- javascript - 加载页面后,文本框中包含值 100。我需要使用 js 将该值显示为 0 到 100 之类的动画。这可能吗?
- angular - Angular ng-packagr 自定义包自动生成的路径问题
- javascript - 如何定位回车键事件?
- python - Python Shutil 模块复制树
- php - 文件夹中的 HTML 文件或 XML 文件中的链接的搜索栏
- android - 如何禁用滚动视图上的水平滚动移动?