gpt4 book ai didi

javascript - 在对象之间创建链接

转载 作者:行者123 更新时间:2023-12-04 08:37:51 25 4
gpt4 key购买 nike

我正在学习 JavaScript,我创建了三个具有某些属性的不同对象:Person、House 和 Car。

let House = function(city, postalCode, street, streetNumber){

this.city = city;
this.postalCode = postalCode;
this.street = street;
this.streetNumber = streetNumber;

return {

getAddress: function() {

return {
'address': {
'city': city,
'postalCode': postalCode,
'street': street,
'streetNumber': streetNumber
}
};

}

};

};

let Person = function(name, surname, yearOfBirth, monthOfBirth, dayOfBirth, bornCity, employment){

this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;
this.monthOfBirth = monthOfBirth;
this.dayOfBirth = dayOfBirth;
this.bornCity = bornCity;
this.employment = employment;

return {

getFullPerson: function() {

return {
'personalInformation': {
'name': name,
'surname': surname,
'dateOfBirth': {
'year': yearOfBirth,
'month': monthOfBirth,
'day': dayOfBirth
},
'bornCity': bornCity
},
'employment': employment,
'home': getAddress(), // pseudocode
'car': getCar() // pseudocode
};

}

};

};
我想在这些对象之间创建一个链接,因为我需要调用,例如,谁住在房子里,反之亦然;但我不清楚如何做到这一点。

最佳答案

这里有一个方法:

let House = function(city, postalCode, street, streetNumber){

this.city = city;
this.postalCode = postalCode;
this.street = street;
this.streetNumber = streetNumber;

return {

getAddress: function() {

return {
'address': {
'city': city,
'postalCode': postalCode,
'street': street,
'streetNumber': streetNumber
}
};

}

};

};

let Person = function(name, surname, yearOfBirth, monthOfBirth, dayOfBirth, bornCity, employment, house, car){

this.name = name;
this.surname = surname;
this.yearOfBirth = yearOfBirth;
this.monthOfBirth = monthOfBirth;
this.dayOfBirth = dayOfBirth;
this.bornCity = bornCity;
this.employment = employment;
this.house = house;
this.car = car;

return {

getFullPerson: function() {

return {
'personalInformation': {
'name': name,
'surname': surname,
'dateOfBirth': {
'year': yearOfBirth,
'month': monthOfBirth,
'day': dayOfBirth
},
'bornCity': bornCity
},
'employment': employment,
'home': (house ? house.getAddress() : null), // pseudocode
'car': (car ? car.getCar() : null) // pseudocode
};

}

};

};

let house1 = new House('city', 'postalCode', 'street', 'streetNumber');

let person1 = new Person('person', '1', 2020, 1, 1, 'bornCity', 'employment', null, null);
let person2 = new Person('person', '2', 2020, 1, 1, 'bornCity', 'employment', house1, null);


console.log(person1.getFullPerson());
console.log(person2.getFullPerson());

创建任何 HouseCar要与 Person 关联的对象.然后你可以选择传入 homecar创建每个对象时的对象 Person .每个 homecar对象将在 Person 中提供其功能。对象也。

关于javascript - 在对象之间创建链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64711287/

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