Skip to content

Instantly share code, notes, and snippets.

@aflansburg
Last active September 27, 2017 03:57
Show Gist options
  • Save aflansburg/d7905a76bcbc3be0c158f2dcb9e96ee6 to your computer and use it in GitHub Desktop.
Save aflansburg/d7905a76bcbc3be0c158f2dcb9e96ee6 to your computer and use it in GitHub Desktop.
Object Composition
const Item = function(name, cost){
this.name = name;
this.isTopLevel = true;
this.baseCost = cost;
this.attributes = [];
this.totalCost = function(){
let total = this.baseCost;
this.attributes.map(x=>{
total += x.cost;
})
return total;
}
this.addAttribute = function(type, value, cost){
this.attributes.push({
type: type,
value: value,
cost: cost
})
}
};
let newShirt = new Item('team tshirt', 16);
newShirt.addAttribute('size', 'extra-large', 5);
newShirt.addAttribute('color', 'blue', 0);
newShirt.addAttribute('logo', './image.png', 12);
newShirt.addAttribute('sleeves', 'short', 0);
console.log(JSON.stringify(newShirt));
console.log(`Total cost: ${newShirt.totalCost()}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment