Advertisement
Guest User

Untitled

a guest
Jul 5th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. function Sale(price) {
  2. this.price = price || 100;
  3. }
  4. Sale.prototype.getPrice = function () {
  5. return this.price;
  6. };
  7.  
  8. Sale.decorators = {}; // 装饰器
  9.  
  10. Sale.decorators.fedtax = {
  11. getPrice: function () {
  12. var price = this.uber.getPrice();
  13. price += price * 5 / 100;
  14. return price;
  15. }
  16. };
  17.  
  18. Sale.decorators.quebec = {
  19. getPrice: function () {
  20. var price = this.uber.getPrice();
  21. price += price * 7.5 / 100;
  22. return price;
  23. }
  24. };
  25.  
  26. Sale.prototype.decorate = function (decorator) {
  27. var F = function () {},
  28. overrides = this.constructor.decorators[decorator],
  29. i, newobj;
  30. F.prototype = this;
  31. newobj = new F();
  32. newobj.uber = F.prototype;
  33. for ( i in overrides) {
  34. if (overrides.hasOwnProperty(i)) {
  35. newobj[i] = overrides[i];
  36. }
  37. }
  38. return newobj;
  39. };
  40.  
  41. var sale = new Sale();
  42. console.log(sale.getPrice()); // 100
  43. sale = sale.decorate('fedtax');
  44. console.log('after fedtax:' + sale.getPrice()); //after fedtax: 105
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement