JS命令模式个人理解

JS命令模式个人理解

//BODY部分
<body> <button id="execute">打开电视</button> <button id="undo">关闭电视</button> </body>
//JavaScript部分
<script> var Tv={//面向字面量 open:function(){ console.log('打开电视机'); }, close:function(){ console.log('关闭电视'); } } var OpenTvCommand=function(receiver){//一个函数,new之后才可以访问receiver this.receiver=receiver; } OpenTvCommand.prototype.execute=function(){//OpenTvCommand中添加一个execute方法 this.receiver.open(); //this.receiver.close(); } OpenTvCommand.prototype.undo=function(){//OpenTvCommand中添加一个undo方法 this.receiver.close(); } var setCommand=function(command){//执行命令函数 document.getElementById('execute').onclick=function(){ command.execute(); //console.log(command); //console.log(OpenTvCommand.execute()); } document.getElementById('undo').onclick=function(){ command.undo(); } } setCommand(new OpenTvCommand(Tv)); //console.log(new OpenTvCommand(Tv)); </script>

分析:

第一步:new OpenTvCommand(Tv) 实例化一个OpenTvCommand(Tv)函数,
        得到一个OpenTvCommand(receiver:Object)对象,
           Object中包含两个对象open()和close()方法

第二步:setCommand(new OpenTvCommand(Tv)) 中的new OpenTvCommand(Tv)可以把它看做open()和close()两个方法传过去,
           传递给setCommand()对象,command.execute()再回到 OpenTvCommand.prototype(execute,undo包含这两个方法)的方法中自由匹配自身函数与TV对象中的方法,
           然后再执行OpenTvCommand.prototype自身有的方法

PS:如何要想在execute或者undo中添加方法,只需添加一个Tv中的方法即可,这就是我理解的命令模式

原文地址:https://www.cnblogs.com/yz-blog/p/6482701.html