I have a menu. It uses a peer class of MenuItem to create and validate menu items:
export class MenuItem {
constructor(data) {
const { name, price, stock = 0, description = "", tags = [] } = data;
// log(arguments);
// Defensive Checks for validation go here...
this._id = String(Math.random());
this.name = name;
this.price = price;
this.stock = stock;
this.description = description;
this.tags = tags;
}
someMethod() {
console.log("blah...");
}
}
The Menu class itself looks like this:
export default class Menu {
#items = []; // Now a private field, so you can't tamper with it from outside this class
constructor(itemsDataArray = []) {
if (!Array.isArray(itemsDataArray)) {
throw new Error(`Items must be an array. Received ${itemsDataArray} (${typeof itemsDataArray})`);
}
for (const itemData of itemsDataArray) {
this.#items.push(new MenuItem(itemData));
}
}
// GET ALL items
getAllItems() {
console.log("superclass getAllItems", this);
return this.#items.slice(); // return a copy, so it can't be affected outside
}
}
This makes a fine READ menu.
I want to inherit this to make a sub-class of EditableMenu
export default class EditableMenu extends Menu {
constructor(itemsDataArray = []) {
super(itemsDataArray);
}
// CREATE an item
addItem(itemData) {
if (!itemData) {
throw new Error(`No data provided to addItem: received ${itemData}`);
}
// Create a new item
const newItem = new MenuItem(itemData);
// push it into our internal array
this.#items.push(newItem);
// Return the finished product for reference
return { ...newItem };
}
}
I made the array of items private in the superclass so that it can't be edited directly but now I just get the error: Uncaught SyntaxError: Private field '#items' must be declared in an enclosing class
Any ideas about how I could approach this. I understand that this is likely syntactic sugar over closures and I wouldn't be sure how to pass a reference between classes without making the array public in the superclass?