-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdecorators.html
110 lines (89 loc) · 2.07 KB
/
decorators.html
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>$title</title>
</head>
<body>
<div id="playground"></div>
<script>
//example
function decorator(func) {
return function() {
return func.apply(this, arguments);
}
}
function sum(a, b) {
return a + b;
}
var getSum = decorator(sum);
console.log( getSum(1,2) ); //3
console.log( getSum(2,3) ); //5
//example
var MacBook = function(){
this.cost = function(){return 41900};
this.screenSize = function(){return 12}
};
var mb = new MacBook();
var MacBookWithLargeMemory = function(){
MacBook.call(this);
this.cost = this.cost() + 10000;
};
var MacBookWithEngraving = function(){
MacBook.call(this);
this.cost = this.cost() + 1000;
};
var MacBookWithInsurance = function(){
MacBook.call(this);
this.cost = this.cost() + 8590;
};
var MacBookWithLargeEngravingInsurance = function(){
MacBook.call(this);
this.cost = this.cost() + 10000 + 1000 + 8590;
};
MacBookWithLargeMemory.prototype = Object.create(MacBook.prototype);
var mbWithLargeMemory = new MacBookWithLargeMemory();
console.log(mbWithLargeMemory); //51900
var mbWithEngraving = new MacBookWithEngraving();
console.log(mbWithEngraving); //42900
var mbWithInsurance = new MacBookWithInsurance();
console.log(mbWithInsurance); //50490
var mbWithLargeEngravingInsurance = new MacBookWithLargeEngravingInsurance();
console.log(mbWithLargeEngravingInsurance); //61490
//example
function MacBook(){
this.cost = function(){return 41900};
this.screenSize = function(){return 12}
}
//Decorator 1
function Memory(mackbook){
var v = mackbook.cost();
mackbook.cost = function(){
return v + 10000;
}
}
//Decorator 2
function Engraving(mackbook){
var v = mackbook.cost();
mackbook.cost = function(){
return v + 1000;
}
}
//Decorator 3
function Insurance(mackbook){
var v = mackbook.cost();
mackbook.cost = function(){
return v + 8590;
}
}
var mb = new MacBook();
Memory(mb);
console.log(mb.cost()); //51900
Engraving(mb);
console.log(mb.cost()); //52900
Insurance(mb);
console.log(mb.cost()); //61490
console.log(mb.screenSize()); //12
</script>
</body>
</html>