-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path状态机2.js
44 lines (39 loc) · 1.05 KB
/
状态机2.js
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
const delegate = function(client, delegation) {
return {
buttonWasPressed() {
return delegation.buttonWasPressed.apply(client, arguments)
}
}
}
const FSM = {
off: {
buttonWasPressed() {
console.log('关灯');
this.button.innerHTML = '下一次我是开灯'
this.currState = this.onState
}
},
on: {
buttonWasPressed() {
console.log('开灯');
this.button.innerHTML = '下一次我是关灯'
this.currState = this.offState
}
}
}
const Light = function() {
this.offState = delegate(this, FSM.off)
this.onState = delegate(this, FSM.on)
this.currState = this.offState // 初始状态
this.button = null;
}
Light.prototype.init = function() {
const button = document.createElement('button')
this.button = document.body.appendChild(button)
this.button.innerHTML = '已关灯'
this.button.onclick = () => {
this.currState.buttonWasPressed()
}
}
const light = new Light()
light.init()