forked from robdodson/JavaScript-Design-Patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
70 lines (57 loc) · 1.36 KB
/
main.js
File metadata and controls
70 lines (57 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Full credit for this example goes to Stoyan Stefanov and his
// amazing book JavaScript Patterns
// http://www.amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752
"use strict";
function Sale(price) {
this.price = price || 100;
}
Sale.prototype.getPrice = function() {
return this.price;
};
Sale.decorators = {};
Sale.decorators.fedtax = {
getPrice: function() {
var price = this._super.getPrice();
price += price * 5 / 100;
return price;
}
};
Sale.decorators.quebec = {
getPrice: function() {
var price = this._super.getPrice();
price += price * 7.5 / 100;
return price;
}
};
Sale.decorators.money = {
getPrice: function() {
return "$" + this._super.getPrice().toFixed(2);
}
};
Sale.decorators.cdn = {
getPrice: function() {
return "CDN$" + this._super.getPrice().toFixed(2);
}
};
Sale.prototype.decorate = function (decorator) {
var F = function () {},
overrides = this.constructor.decorators[decorator],
i,
newobj;
// Create prototype chain
F.prototype = this;
newobj = new F();
newobj._super = F.prototype;
// Mixin properties/methods of our decorator
// Overriding the ones from our prototype
for (i in overrides) {
if (overrides.hasOwnProperty(i)) {
newobj[i] = overrides[i];
}
}
return newobj;
};
var sale = new Sale(50);
sale = sale.decorate('fedtax');
sale = sale.decorate('cdn');
console.log(sale.getPrice());