前端学习心得-javascript设计模式与开发实践-命令封装模式

本文通过一个具体实例介绍了命令模式的应用,包括如何将请求封装为对象、实现Switch函数、设定及调用指令等步骤,并分享了一些实践过程中的注意事项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

命令封装模式主要用于分离请求的发起者与接受者

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类型判断的心得,先不做讲述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值