Change before you have to.

Prototype chain by Object.create()

2017-07-19

Coffee, tea and prototypes

讓我們以飲料作為例子,使用咖啡及茶來完成 prototype chain 的範例。要旨在於專注要做什麼 (waht to do),而不是你是誰 (who you are),利用委任的概念(delegation)將同一層級的行為封裝在一起,越上層的行為越一般化,越下層的行為越特定話,然後使用ES5所提供的 Object.create() 來實作原型鍊(prototype chain)。

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
// beverage for coffee and tea to initialize actions
const beverage = {
init({name}) {
this.name = name
if (this.checkIfProcessComplete()) {
this.makeDrink()
} else {
console.log(`You have missed some steps for your ${this.name}. Please check again.`)
}
},
makeDrink() {
this.boilWater()
this.brew()
this.pourInCup()
this.addCordiments()
},
checkIfProcessComplete() {
return (this.boilWater && this.brew && this.pourInCup && this.addCordiments)
}
}
// coffee implementation
const coffee = Object.create(beverage)
coffee.boilWater = function() {
console.log(`boil water for ${this.name}`)
}
coffee.brew = function() {
console.log(`brew for ${this.name}`)
}
coffee.pourInCup = function() {
console.log(`pour in cup for ${this.name}`)
}
coffee.addCordiments = function() {
console.log(`add cordiments for ${this.name}`)
}
// tea implementation
const tea = Object.create(beverage)
tea.boilWater = function() {
console.log(`boil water for ${this.name}`)
}
tea.brew = function() {
console.log(`brew for ${this.name}`)
}
tea.pourInCup = function() {
console.log(`pour in cup for ${this.name}`)
}
tea.addCordiments = function() {
console.log(`add cordiments for ${this.name}`)
}
// one type of coffee
const espresso = Object.create(coffee)
// one type of tea
const herbals = Object.create(tea)
espresso.init({name: 'good espresso'}) // real coffee to drink
herbals.init({name: 'black tea'}) // real tea to drink

Blog comments powered by Disqus