Show toolbar

2013年10月18日 星期五

Fluent Interface with Prototype

標題:流暢介面搭配Prototype屬性的用法
JavaScript (index.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
<span id="fatty"></span> V.S. <span id="thin"></span>
<script type="text/javascript">
var Runner = function(e) {
this.speed = e.speed; //Meters per second
this.time = null; //Second
this.distance = null; //Meter
};
Runner.prototype.ready = function(e) {
this.time = 0; //Cost time
this.distance = e.starting; //Starting point
return this;
};
Runner.prototype.run = function(e) {
this.time += e.second;
this.distance += this.speed * e.second; // Distance = Speed * Time
return this;
};
Runner.prototype.halt = function(e) {
this.time += e.second;
return this;
};
Runner.prototype.result = function(e) {
document.getElementById(e.id).innerHTML = "Distance:" + this.distance + " m, Cost time:" + this.time + " sec";
return this;
};
var fatty = new Runner({speed:2}); //Speed: 2m/s
fatty.ready({starting:10}).run({second:30}).halt({second:5}).run({second:15}).result({id:"fatty"});
var thin = new Runner({speed:2.5}); //Speed: 2.5m/s
thin.ready({starting:0}).run({second:40}).result({id:"thin"});
</script>

範例結果:
Distance:100 m, Cost time:50 sec V.S. Distance:100 m, Cost time:40 sec

說明:
此程式使用流暢介面搭配Prototype屬性的方式撰寫,
計算胖與瘦的人100公尺跑步的時間(不計加減速),
條件項目:
1. 胖者速度為每秒2公尺 - Runner({speed:2})
2. 瘦者速度為每秒2.5公尺 - Runner({speed:2.5})
3. 瘦者禮讓胖者由10公尺處起跑 - ready({starting:10})
4. 胖者跑了30秒以後,休息了5秒,再繼續跑了15秒 - run({second:30}).halt({second:5}).run({second:15})
5. 瘦者跑了40秒全程無休息 - run({second:40})

沒有留言:

張貼留言