命令封装模式主要用于分离请求的发起者与接受者
1、把请求封装为对象
var TV = {
name: "tv",
open: function(){
SwitchObj("#0f0");
console.log("打开")
},
close: function(){
SwitchObj("#f00");
console.log("关闭")
}
}
var air_conditioner = {//shen
name: "air_conditioner",
open: function(){
SwitchObj("#0f0");
console.log("air_conditioner 打开")
},
close: function(){
SwitchObj("#f00");
console.log("air_conditioner 关闭")
}
}
var openCommand = function(receiver){//指定接收方
console.log("execute receiver:"+receiver.name);
this.receiver = receiver;
}
openCommand.prototype.execute = function(){
this.receiver.open();
}
openCommand.prototype.undo = function(){
this.receiver.close();
}
2、Switch函数
function SwitchObj(color){
var _obj = document.getElementById("show");
_obj.style.backgroundColor = color;
}
3、设定指令
var setCommand = function(command){//设置指令发起以及接受对象
document.getElementById("open").addEventListener("click",function(){
command.execute();
})
document.getElementById("close").addEventListener("click",function(){
command.undo();
})
}
function isArray(o){
return Object.prototype.toString.call(o)=='[object Array]';
}
var executeSetOpenCommand = function(executeQue){
if(isArray(executeQue)){
for(var i=0; i<executeQue.length; i++){
setCommand(new openCommand(executeQue[i]));
}
}
}
4、调用
// setCommand(new openCommand(TV));//设定指令 传入指令对象以及指令方法
// setCommand(new openCommand(air_conditioner));
executeSetOpenCommand([TV,air_conditioner])
5、执行结果
6、踩坑
- addEventListener和onclick
因为书中案例只设置TV实体的指令,并且用的是onclick绑定方式。
个人又加了一个air_conditioner,但是控制台只输出了air_conditioner的日志,经过调试发现TV的绑定事件被覆盖所以没有触发,将onclick换成addEventListener后程序 完美运行
- 判断isArray
后期准备单独写一篇js类型判断的心得,先不做讲述