peterschussheim
10/26/2016 - 6:46 PM

decorators

decorators

///This is an example of using decorators to extend the functionality of the base constructor MacBook function.\\\\ that starts with:\\\\- generic "macbook" constructor function with properties initialized to a 'base' or starting value that we can extend with one or more decorators.

// The constructor to decorate ///Begin with a generic constructor function
function MacBook() {
 
  this.cost = function () { return 997; };
  this.screenSize = function () { return 11.6; };
 
}
 
// Decorator 1
function memory( macbook ) { ///Simple example decorator that handles the functionality of adding an upgraded memory option.
 
  var v = macbook.cost();
  macbook.cost = function() {
    return v + 75;
  };
 
}
 
// Decorator 2
function engraving( macbook ){
 
  var v = macbook.cost();
  macbook.cost = function(){
    return v + 200;
  };
 
}
 
// Decorator 3
function insurance( macbook ){
 
  var v = macbook.cost();
  macbook.cost = function(){
     return v + 250;
  };
 
}
 
var mb = new MacBook();
memory( mb );
mb.memory
engraving( mb );
insurance( mb );
 
// Outputs: 1522
mb.cost();
 
// Outputs: 11.6
mb.screenSize();

decorators

This Gist was automatically created by Carbide, a free online programming environment.

You can view a live, interactive version of this Gist here.