Decorator example

by Richard Hunter

JavaScript

/* Decorator from Javascript patterns by Stoyan Stefanov */

function Product(id) {
	this.fields = {
    	id : id,
        name : '',
        price : '',
        unit : 'default'
    };
}
Product.prototype.getFields = function () {
	return this.fields;
};
Product.prototype.decorate = function (decorator) {
	var F = function () {},
        overrides = this.constructor.decorators[decorator],
        i, 
        newobj;
	F.prototype = this;
    newobj = new F();
    newobj.uber = F.prototype;
   	for(i in overrides) {
    	if(overrides.hasOwnProperty(i)) {
        	newobj[i] = overrides[i]
        }
    }
    return newobj;

}

Product.decorators = {};

Product.decorators.fruit = {
    fields : {
    	unit : 'kg',
        storageInstructions : 'dfdfd'
    
    },
    
	getFields : function () {
		return _.extend({}, this.uber.getFields(), this.fields);
	}
};



var product = new Product('alpha');
var apple = product.decorate('fruit');

console.log(apple.getFields());