gpt4 book ai didi

javascript - 街道未定义javascript中的错误

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

我是 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();

上面的代码显示错误

Uncaught ReferenceError: street is not defined at Object.showAddress

最佳答案

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

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

When a function is called as a method of an object, its this is set to the object the method is called on

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();

关于javascript - 街道未定义javascript中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56312642/

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