Created
March 5, 2013 19:56
-
-
Save Sljubura/5093688 to your computer and use it in GitHub Desktop.
Decorator pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Constructor | |
function Sale(price) { | |
this.price = price || 10 | |
} | |
Sale.prototype.getPrice = function () { | |
return this.price; | |
}; | |
Sale.decorators = {}; | |
Sale.decorators.statetax = { | |
getPrice: function () { | |
var price = this.uber.getPrice(); | |
price += price * 2 / 100; | |
return price; | |
} | |
}; | |
Sale.decorators.incometax = { | |
getPrice: function () { | |
var price = this.uber.getPrice(); | |
price += price * 3 / 100; | |
} | |
}; | |
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
var sale = new Sale(100);
sale.decorate('fedtax');// цена 100 долларов
sale.decorate('quebec');// добавить федеральный налог
sale.decorate('money');// форматировать как денежную сумму
sale.getPrice();// “$112.88”
Не работает, $112,88 не получится