控制灯的开关,关 -> 弱灯 -> 强灯 -> 关灯 循环,这里使用状态模式来设计,省去了大量的if else判断,并且方便宜以后扩展其它状态。直接上代码:
// 灯函数
const light = function(){
this.ruo = new ruo(this)
this.qiang = new qiang(this)
this.guan = new guan(this)
this.btn = document.createElement('button')
document.body.appendChild(this.btn)
//初始化灯为关的状态,省电
this.setState(this.guan)
}
//点击灯开关回调
light.prototype.setState = function(newState){
this.curr = newState
this.btn.innerHTML = this.curr.btnName
this.btn.onclick = this.curr.btnclick.bind(this)
}
//弱灯状态,点击变强灯
const ruo = function(light){
this.btnName = '点击变强灯'
this.light = light
}
ruo.prototype.btnclick = function(){
this.setState(this.qiang)
}
//强灯状态,点击关灯
const qiang = function(light){
this.btnName = '点击关灯'
this.light = light
}
qiang.prototype.btnclick = function(){
this.setState(this.guan)
}
//关灯状态,点击变弱灯
const guan = function(light){
this.btnName = '点击开弱灯'
this.light = light
}
guan.prototype.btnclick = function(){
this.setState(this.ruo)
}
//创建灯实例
new light()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)