I'm trying to learn JavaScript. I'm working on a problem where I'm making a grocery list: an array of sub-arrays that contain item, quantity and price. From there I plan to add items, read back the list, remove items, etc. My current issue is I cannot access sub-methods. I can't seem to find documentation on how to do it - but I keep reading that these methods are private? So maybe I'm way off base. I can't figure out how else I could set this up so multiple methods all talk to each other.
var groceryList = function(food, quantity, price) {
this.item = {};
this.items = {food:food, quantity:quantity, price:price};
return this.items
this.addStuff = function(food, quantity, price) {
this.items.push({food:food, quantity:quantity, price:price});
return this.items
};
this.tallyList = function() {
return items.length;
}
}
var myList = new groceryList("cookie", 2, 1.00);
console.log(myList)
myList.addStuff("brownie", 1, 2.50);
console.log(myList.tallyList);
return this.itemsin the middle of the function. Also,tallyListis a method, so you need to call it (myList.tallyList()). Also, you can't declare something withthis.and then not use it later (intallyList). Also, you declaredthis.itemsas an object literal, yet you're treating it as an array - declare it as an array:this.items = [{food:food, quantity:quantity, price:price}];. Here's an example: jsfiddle.net/m8hwsj6a