Romann,
var id = "1"; // id товара
var name = "item 2"; // переменная имени
var x = 1;
var price = 500;
function Cart(id, name, price, x) {
var foo = localStorage.getItem("foo");
foo = foo ? JSON.parse(foo) : {};
foo.sum = function(id) {
return id in this ? this[id][2] * this[id][3] : 0
};
Object.defineProperty(foo, "sum", {
enumerable: false
});
Object.defineProperty(foo, "total", {
enumerable: false,
get: function() {
return Object.keys(this).reduce(function(s, a) {
return s + foo.sum(a)
}, 0)
}
});
if (id != void 0) {
var item = foo[id];
var text = "обновляем товар";
if (!(id in foo)) {
foo[id] = [id, name, price, 0];
text = "добавляем новый товар"
}
foo[id][3] += x;
localStorage.setItem("foo", JSON.stringify(foo));
alert(text)
}
return foo
};
var foo = Cart(id,name,price,x);
console.log(foo.sum(1),foo.total)