Prototypal inheritance
by jhoguet
JavaScript
function log (){
$('body').append('<p>' + arguments[0] + '</p>');
}
function GroceryItem(){
var _weight = '12 oz';
this.weight = function(weight){
if (weight){
// do some business logic against weight
_weight = weight;
}
return _weight;
}
}
function CartItem(){
}
CartItem.prototype = new GroceryItem();
var item1 = new CartItem();
var item2 = new CartItem();
log(item1.weight());
log(item2.weight());
// 12 oz
// 12 oz
// then we only change one of them
item1.weight('8 oz');
log(item1.weight());
log(item2.weight());
// 8 oz
// 8 oz
//prototypal inheritance does not work well when doing any private (closure) state
// also, you lose the ability to "inherit" any object creation (ctor) logic because the base constructor is not called once per
// this is why I prefer
//function CartItem(){
// GroceryItem.apply(this, null);
//}