【发布时间】:2016-04-29 11:26:15
【问题描述】:
我正在尝试创建一个简单的练习程序,它有一个Store 构造函数,它接收一个inventoryList 数组,一个InventoryItem 构造函数,它创建一个要存储在inventoryList 数组中的每个项目的对象.我想向InventoryItem 列表添加一个方法,该方法将采用一个数字并将其添加到列表中的每个项目中。以下是我的代码:
var Store = function(inventory){
this.inventory = inventory;
}
var InventoryItem = function(cost, color, size){
this.cost = cost;
this.color = color;
this.size = size;
}
//create each inventory item as an object
var lamp = new InventoryItem(40.00, 'blue', 'small');
var throwPillow = new InventoryItem(25.00, 'yellow', 'medium');
var sconce = new InventoryItem( 18.00, 'gold', 'large');
var candles = new InventoryItem(10.00, 'white', 'small');
var curtains = new InventoryItem(30.00, 'purple', 'large');
//store inventory items into an inventory object
var inventorylist = [lamp, throwPillow, sconce, candles, curtains];
// add number of items to each item
InventoryItem.prototype.howMany = function(num){
function addCount(inventorylist){
for(var i = 0; i < inventorylist.length; i++){
inventorylist[i].howMany = num;
}
}
}
//store inventory within a store
var deannaStore = new Store(inventorylist);
var dionStore = new Store(inventorylist);
var mikeStore = new Store(inventorylist);
当我尝试向列表中的项目添加数字时遇到问题
例如:dionStore.howMany(15)
这给了我错误:Uncaught TypeError: dionStore.howMany is not a function
任何帮助都将不胜感激,最好能详细解释为什么这不起作用。
【问题讨论】:
-
InventoryItem.prototype.howMany应该是Store.prototype.howMany -
如果我要为每个项目添加计数,为什么它会出现在商店原型而不是库存项目上?这也会产生同样的错误
标签: javascript arrays methods constructor prototype