2 回答
TA贡献1851条经验 获得超4个赞
这是一个方法:
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());
创建您想要与 关联的任何House或对象。然后,您可以选择在创建每个 时传入或对象。每个或对象也将在该对象内具有可用的功能。CarPersonhomecarPersonhomecarPerson
TA贡献1773条经验 获得超3个赞
据我所知,您希望在 Person 对象中引用一个人的房屋和汽车。因此,要使其工作,您唯一需要做的就是将 House 和 Car 对象传递给 Person:
let Person = function (
name,
surname,
yearOfBirth,
monthOfBirth,
dayOfBirth,
bornCity,
employment,
home,
car
) {
this.name = name
this.surname = surname
this.yearOfBirth = yearOfBirth
this.monthOfBirth = monthOfBirth
this.dayOfBirth = dayOfBirth
this.bornCity = bornCity
this.employment = employment
this.home = home
this.car = car
return {
getFullPerson: function () {
return {
personalInformation: {
name: name,
surname: surname,
dateOfBirth: {
year: yearOfBirth,
month: monthOfBirth,
day: dayOfBirth,
},
bornCity: bornCity,
},
employment: employment,
home: home.getAddress(),
car: car.getCar(),
}
},
}
}
添加回答
举报