Created
March 14, 2017 12:49
-
-
Save hereisfun/99576c71ea17762c2fcb6bd60a937c2c to your computer and use it in GitHub Desktop.
状态模式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//状态模式 | |
//重点在于状态机的切换逻辑,以及有相同的方法代理操作(如这里的btnpressed) | |
var STATUS = { | |
on: { | |
btnpressed: function(){ | |
console.log('关灯了'); | |
this.button.innerHTML = 'ON'; | |
this.currentstatus = STATUS.off; | |
} | |
}, | |
off:{ | |
btnpressed: function(){ | |
console.log('开灯了'); | |
this.button.innerHTML = 'OFF'; | |
this.currentstatus = STATUS.on; | |
} | |
} | |
} | |
function Light(){ | |
this.currentstatus = STATUS.off; | |
this.button = null; | |
} | |
Light.prototype.init = function(){ | |
var that = this; | |
var btn = document.createElement('button'); | |
btn.innerHTML = 'ON'; | |
document.body.appendChild(btn); | |
this.button = btn; | |
this.button.onclick = function(){ | |
//绑定this,避免丢失 | |
that.currentstatus.btnpressed.call(that); | |
} | |
} | |
var light = new Light(); | |
light.init(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment