Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Last active May 19, 2017 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SoarLin/fa483d96f21735491bd55f52a79b3a6a to your computer and use it in GitHub Desktop.
Save SoarLin/fa483d96f21735491bd55f52a79b3a6a to your computer and use it in GitHub Desktop.
Decorator 實作範例 1
function Sale(price) {
this.price = price || 100;
}
Sale.prototype.getPrice = function() {
return this.price;
};
Sale.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;
};
Sale.decorators = {};
Sale.decorators.fedtax = {
getPrice: function() {
var price = this.uber.getPrice();
price += price * 0.05;
return price;
}
};
Sale.decorators.quebec = {
getPrice: function() {
var price = this.uber.getPrice();
price += price * 0.075;
return price;
}
};
Sale.decorators.money = {
getPrice: function() {
return '$' + this.uber.getPrice().toFixed(2);
}
};
Sale.decorators.cdn = {
getPrice: function() {
return 'CDN$' + this.uber.getPrice().toFixed(2);
}
};
var sale = new Sale(100);
sale = sale.decorate('fedtax');
sale = sale.decorate('quebec');
sale = sale.decorate('money');
console.log(sale.getPrice());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment