有人能在这里发现错误吗?检查点1触发但不检查检查点2.无法弄清楚我的陈述有什么问题。
<script>
function shoppingCart() {
var item,
price,
qty,
items = {
itemID: "B17",
itemPrice: 17,
itemQty: 1
};
function addItem(item, price, qty) {
alert("checkpoint 1");
items.push({
itemID: item,
itemPrice: price,
itemQty: qty
});
alert("checkpoint 2");
};
};
cart = new shoppingCart();
cart.addItem("b4",14,1);
alert(cart.items.itemID);
</script>
答案 0 :(得分:3)
items = {
itemID: "B17",
itemPrice: 17,
itemQty: 1
};
不是数组。它应该是:
items =[{
itemID: "B17",
itemPrice: 17,
itemQty: 1
}];
答案 1 :(得分:2)
问题是项目不是数组,而是对象。小提琴:http://jsfiddle.net/pCc9w/
所有代码,已修复:
function shoppingCart() {
var item,
price,
qty;
this.items = [{
itemID: "B17",
itemPrice: 17,
itemQty: 1
}];
};
shoppingCart.prototype.addItem = function(item, price, qty) {
alert("checkpoint 1");
this.items.push({
itemID: item,
itemPrice: price,
itemQty: qty
});
alert("checkpoint 2");
};
cart = new shoppingCart();
cart.addItem("b4",14,1);
alert(cart.items[1].itemID);