Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function Sale(price) {
- this.price = price || 100;
- }
- Sale.prototype.getPrice = function () {
- return this.price;
- };
- Sale.decorators = {}; // 装饰器
- Sale.decorators.fedtax = {
- getPrice: function () {
- var price = this.uber.getPrice();
- price += price * 5 / 100;
- return price;
- }
- };
- Sale.decorators.quebec = {
- getPrice: function () {
- var price = this.uber.getPrice();
- price += price * 7.5 / 100;
- return 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;
- };
- var sale = new Sale();
- console.log(sale.getPrice()); // 100
- sale = sale.decorate('fedtax');
- console.log('after fedtax:' + sale.getPrice()); //after fedtax: 105
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement