Pro javascript design pattern 读书笔记之 Using callbacks to retrieve Date from chained methods and chapter summary
2008-10-31 15:17 wlstyle 阅读(255) 评论(0) 收藏 举报Using callbacks to retrieve Date from chained methods
在一些情况下,把方法Chain在一起不是一个好的想法。对于 设置属性(mutaor根据语境翻译也可以认为是写入的方法) 的方法,链式的方法可能刚刚好,但是对于访问属性(accessor根据语境翻译也可以认为是读取属性的方法)的方法,你可能希望返回你请求数据。而不是当前对象(this)。然后如果链是你最终的想法同时希望方法结合在一起,你能通过使用回调函数返回数据来解决这个问题。下个例子将展示这两种技术。API类使用通常的访问(这样就打破了链),而API2使用了回调的方法 。
1 /*accessor without function callback:return requested data in accessors */
2
3 var API = function(){ };
4
5 API.prototype = {
6
7 name: 'hello',
8
9 //privileged mutator method
10
11 setName: function(newName){
12
13 this.name = newName;
14
15 return this;
16
17 },
18
19 //privileged accessor method
20
21 getName: function(){
22
23 return this.name;
24
25 }
26
27 };
28
29 //implementtation code
30
31 var la = new API();
32
33 alert(la.getName());//output hello
34
35 alert(la.setName('piaopiao').getName());//output piaopiao
36
37 var API2 = function(){
38
39 };
40
41 API2.prototype = {
42
43 name: 'hello',
44
45 //privileged mutator method
46
47 setName: function(newName){
48
49 this.name = newName;
50
51 return this;
52
53 },
54
55 //privileged accessor method
56
57 getName: function(callback){
58
59 callback.call(this);
60
61 return this;
62
63 }
64
65 };
66
67 //implementtation code
68
69 var la = new API2();
70
71 la.getName(function(){alert(this.name)}).setName('piaopiao').getName(function(){alert(this.name)});
72
73 //first output hello then output piao
74
75
2
3 var API = function(){ };
4
5 API.prototype = {
6
7 name: 'hello',
8
9 //privileged mutator method
10
11 setName: function(newName){
12
13 this.name = newName;
14
15 return this;
16
17 },
18
19 //privileged accessor method
20
21 getName: function(){
22
23 return this.name;
24
25 }
26
27 };
28
29 //implementtation code
30
31 var la = new API();
32
33 alert(la.getName());//output hello
34
35 alert(la.setName('piaopiao').getName());//output piaopiao
36
37 var API2 = function(){
38
39 };
40
41 API2.prototype = {
42
43 name: 'hello',
44
45 //privileged mutator method
46
47 setName: function(newName){
48
49 this.name = newName;
50
51 return this;
52
53 },
54
55 //privileged accessor method
56
57 getName: function(callback){
58
59 callback.call(this);
60
61 return this;
62
63 }
64
65 };
66
67 //implementtation code
68
69 var la = new API2();
70
71 la.getName(function(){alert(this.name)}).setName('piaopiao').getName(function(){alert(this.name)});
72
73 //first output hello then output piao
74
75
Summary
Javascript 能通过引用传递所有的对象,所以你能在每个方法中传递这些引用.通过在每个方法的最后返回this(当前对象),你能创建一个可以链的类,这个模式帮助流线型的代码,在一定程度上更优雅和简洁。通常你能避免对象重新定义好几次的情况,同时使用链可以减少代码量。如果你希望为你的类的接口一致同时又希望可以链式写入属性和访问属性的方法。你能为你的访问方法添加回调函数。
浙公网安备 33010602011771号