我正在尝试将一个对象分配给另一个对象的属性。
那是真实项目的模型。在这里,我参加了一场比赛,有各种各样的汽车,并拥有一名驾驶员。驱动程序属性是一个对象。在控制台输出处,我想要一辆带有驾驶员名字的汽车。
<script>
let carsNames = ["Ferrari", "Mercedes", "Maserati", "Renault"];
let drivers = ["Ayrton", "Alain", "Michael", "Nikki"];
let Car = (function (_team, _driver) {
let team = _team;
let driver = _driver;
return {
getTeam: function () {
return team;
},
getDriver: function () {
return driver;
}
}
});
let Driver = (function (_name) {
let name = _name;
return {
getName: function () {
}
}
});
let Race = (function () {
cars = [];
for (let i = 0; i < carsNames.length; i++) {
driver = new Driver(drivers[i]);
car = new Car(carsNames[i], driver);
cars.push(car);
}
return {
getCars: function () {
return cars;
}
}
});
let GPSyldavie = new Race();
let myrace = GPSyldavie.getCars();
myrace.forEach(function (mr) {
console.log(mr.getTeam(), mr.getDriver().getName());
})
// Console output :
// Ferrari undefined
// Mercedes undefined
// Maserati undefined
// Renault undefined
</script>
重点是约束驾驶员的宽度à汽车,但我无法告诉汽车它是由驾驶员驾驶的。
答案 0 :(得分:0)
您的getName函数不返回任何内容...
let Driver = (function (_name) {
let name = _name;
return {
getName: function () {
}
}
});
应该看起来更像...
let Driver = (function (_name) {
let name = _name;
return {
getName: function () {
return name;
}
}
});