1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>javascript高级语法17-装饰者模式下</title>
6 </head>
7 <body>
8 <div id="demo2">
9
10 </div>
11
12 <script type="text/javascript">
13 //装饰者可以用在类上,也可以用在函数上
14 function demo1(){
15 //写一个装饰者函数,函数的目的是把目标函数的返回值变成大写
16 function upperCase(fun){
17 return function(){
18 return fun().toUpperCase();
19 }
20 }
21 //被封装的函数
22 function getDate(){
23 return new Date().toString();
24 }
25 //执行装饰
26 var getDateCaps = upperCase(getDate);
27 document.write(getDate());
28 document.write("<br>")
29 document.write(getDateCaps());
30 /*如果原有的功能不适合你的项目,需要大量扩充原油功能
31 * 并且不想改变原有的接口,那么可以用装饰者模式。
32 */
33 }
34 //demo1();
35
36
37 function demo2(){
38 //装饰者完成对函数性能测试的任务
39 var listBuilder = function(el,listSize){
40 this.el = document.getElementById(el);
41 this.size = listSize;
42 //创建列表
43 this.Buildlist = function(){
44 var root = document.createElement("ol");
45 this.el.appendChild(root);
46 for(var i=0;i<this.size;i++){
47 var li = document.createElement("li");
48 root.appendChild(li);
49 }
50 }
51 };
52 var list = new listBuilder("demo2",8000);
53 //list.Buildlist();
54 //利用装饰者检测函数执行的时间
55
56 var simpleProfiler = function(component){
57 this.component = component;
58 this.ListBuilder = function(){
59 var startDate = new Date().getTime();
60 this.component.Buildlist()
61 var endDate = new Date().getTime();
62 alert(endDate - startDate);
63 }
64 }
65 //new simpleProfiler(list).ListBuilder();
66 //改造为通用的装饰者,可以完成所有函数的效率测试。
67
68 var simpleProfiler2 = function(component){
69 this.component = component;
70 this.action = function(methodName){
71 var self= this;
72 var method = component[methodName];
73 //如果是函数那就进行装饰
74 if(typeof method == "function"){
75 var startDate = new Date().getTime();
76 method.apply(self.component,arguments);
77 var endDate = new Date().getTime();
78 alert(endDate - startDate);
79 }
80 }
81 }
82
83 new simpleProfiler2(list).action("Buildlist");
84
85 }
86 demo2();
87
88 </script>
89 </body>
90 </html>