zoukankan      html  css  js  c++  java
  • 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中的方法即可,这就是我理解的命令模式

  • 相关阅读:
    fiddler应用之Composer(发送接口请求)
    fiddler应用之AutoResponder(fiddler的重定向页面功能)
    fiddler应用之设置断点(fiddler篡改request和response数据)
    fiddler应用之过滤器(用fiddler筛选特定网络请求)
    fiddler配置之对移动设备进行抓包证书安装
    fiddler配置之设置手机代理
    外部排序的基本概念
    80天考研核心短语
    地址访问冲突问题(四体交叉存取)
    制约函数法
  • 原文地址:https://www.cnblogs.com/yz-blog/p/6482701.html
Copyright © 2011-2022 走看看