Skip to content

Instantly share code, notes, and snippets.

@hereisfun
Created March 14, 2017 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hereisfun/99576c71ea17762c2fcb6bd60a937c2c to your computer and use it in GitHub Desktop.
Save hereisfun/99576c71ea17762c2fcb6bd60a937c2c to your computer and use it in GitHub Desktop.
状态模式
//状态模式
//重点在于状态机的切换逻辑,以及有相同的方法代理操作(如这里的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