gpt4 book ai didi

javascript - 正确实例化复杂的 JS 对象

转载 作者:行者123 更新时间:2023-12-03 02:32:20 25 4
gpt4 key购买 nike

我正在通过 Web 服务获取数据,并且想用地址对象填充我的对象 User。

当尝试为对象 this.user.address.residentialAddress 赋值时,我得到了

ERROR TypeError: Cannot set property 'residentialAddress' of undefined

尝试使用构造函数实例化时会出现相同的错误。简单console.log(this.user.address.residentialAddress.City);输出值。

我的猜测是我没有正确创建对象,但我看不到解决方案?

private user: MyUser;
...
this.user = new MyUser();

this.user.address.residentialAddress = {
City: data.address.residentialAddress.City,
StreetAddress: data.address.residentialAddress.StreetAddress,
Suburb: data.address.residentialAddress.Suburb,
Province: data.address.residentialAddress.Province
};


export class Address {
public StreetAddress: string;
public Suburb: string;
public City: string;
public Province: string;

constructor(street: string, suburb: string, city: string, province: string){
this.StreetAddress = street;
this.Suburb = suburb;
this.City = city;
this.Province = province;
}
}

export class MyUser {
address: {
residentialAddress: Address;
postalAddress: Address;
}
....

}

最佳答案

我认为你应该将地址放在构造函数中:

export class MyUser {    
public address: object;
constructor(){
this.address = {
residentialAddress: Address;
postalAddress: Address;
}
}

}

这将使user.address在实例化后被定义,并且Cannot set property 'residentialAddress' of undefined应该消失。

关于javascript - 正确实例化复杂的 JS 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48682759/

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