我正在尝试使用getter和setter编写一个简单的对象,但我不完全确定此代码是否正确,对于使用下划线的实例,我也有些困惑。我得到的当前错误是menu.addDishToCourses is not a function
,但是控制台记录了进餐,将其属性显示为一个函数。是什么赋予了?
let menu = {
_courses: {
_appetizer: [],
_main: [],
_dessert: [],
get appetizers() {
return this._courses.appetizer;
},
set appetizers(appetizerInput) {
this._courses.appetizer = appetizerIn;
},
get mains() {
return this._courses.main;
},
set mains(mainsInput) {
this._courses.main = mainsInput;
},
get desserts() {
return this._courses.dessert;
},
set desserts(dessertsInput) {
this._courses.deseserts = dessertInput;
},
get courses() {
return {
appetizers: this._courses.appetizer,
mains: this._courses.main,
desserts: this._courses.dessert,
};
},
addDishToCourses(courseName, dishName, dishPrice) {
const dish = {
name: dishName,
price: dishPrice,
};
this._courses[courseName].push(dish);
},
getRandomDishFromCourse(courseName) {
const dishes = this._courses[courseName];
const RandomIndex = Math.floor(Math.random() * dishes.length);
return dishes[RandomIndex];
},
generateRandomMeal() {
let appetizer = this.getRandomDishFromCourse('appetizer');
let main = this.getRandomDishFromCourse('main');
let dessert = this.getRandomDishFromCourse('dessert');
let totalPrice = appetizer.price + main.price + dessert.price;
return `You order and appetizer ${appetizer.name},${main.name} and a main dish ${main.price} and a dessert ${dessert.price}. Total price was $${totalProice}. `;
},
}
};
menu.addDishToCourses('_appetizer', 'pepperoni', 5.43);
menu.addDishToCourses('_mains', 'steak', 18.0);
menu.addDishToCourses('_dessert', 'pie', 3.5);
最佳答案
您有范围问题。您的getter和setter方法中的this
是指_courses
的menu
属性,而不是menu
对象本身。
您可能想要设计类似于以下内容的menu
对象:
let menu = {
_courses: {
_appetizer: [],
_main: [],
_dessert: [],
get appetizer() {
return this._appetizer
},
get main() {
return this._main
},
get dessert() {
return this._dessert
}
},
get courses() {
return {
appetizers: this._courses.appetizer,
main: this._courses.main,
desserts: this._courses.dessert,
};
},
addDishToCourses(courseName, dishName, dishPrice) {
let dish = {
name: dishName,
price: dishPrice,
};
//console.log(this._courses[courseName]);
this._courses[courseName].push(dish);
}
};
menu.addDishToCourses('_appetizer', 'pepperoni', 5.43);
menu.addDishToCourses('_main', 'steak', 18.0);
menu.addDishToCourses('_dessert', 'pie', 3.5);
console.log(menu.courses);
就带下划线的命名属性而言,这只是命名私有变量的JavaScript约定(因为您将使用面向公众的getter和setter方法访问那些私有变量)。下划线实际上并没有做任何事情。
关于javascript - 正确编写带有函数的getter和setter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49886035/