I have a basic library I created as follows:
(function () {
function Store() {
var store = [];
if (!(this instanceof Store)) {
return new Store();
}
this.add = function (name, price) {
store.push(new StoreItem(name, price));
return this;
};
}
function StoreItem(name, price) {
if (!(this instanceof StoreItem)) {
return new StoreItem();
}
this.Name = name || 'Default item';
this.Price = price || 0.0;
}
Store.prototype.toString = function () {
// build a formatted string here
};
StoreItem.prototype.toString = function () {
return this.Name + ' $' + this.Price;
};
window.shop = window.shop || {
Store: function () {
return new Store();
}
};
}());
The large majority of this works well! However, I do not want to expose my store
array defined in the Store constructor as I do not want it modified in anyway outside this library's control.
But, on the contrary, I would like to override the Store
's toString
method to make use of the StoreItem
s in the store
array so I can return a formatted string of all the StoreItem
s using its toString
method.
E.g. if store
was exposed, the toString
method would look something like:
Store.prototype.toString = function () {
return this.store.join('\r\n');
};
// shop.Store().add('Bread', 2).add('Milk', 1.5).toString() result:
// Bread $2
// Milk $1.5
Is there anyway I can achieve this without exposing my store
array publicly?