使用闭包来实现一个完整的面向对象系统

//面向对象的方式
var Tv={
  open:function(){
    alert('打开');
  },
  close:function(){
    alert('关闭');
  }
};

var CreateCommand = function(rececier){
  this.rececier = rececier;
};
CreateCommand.prototype = {
  execute : function(){
    this.rececier.open();
  },
  undo : function(){
    this.rececier.close();
  }
};
var setCommand = function(command){
  document.getElementById('execute').onclick = function(){
  command.execute();
  };
  document.getElementById('undo').onclick = function(){
  command.undo();
  };
};

setCommand( new CreateCommand(Tv));


//闭包的方式
var Tv={
  open:function(){
    alert('打开');
  },
  close:function(){
    alert('关闭');
  }
};

var CreateCommand = function (rececier){
  var execute = function(){
    rececier.open();
  };
  var undo = function(){
  rececier.close();
  };

  return {
    execute:execute,
    undo:undo
   };
};

var setCommand = function(command){
    document.getElementById('execute').onclick = function(){
    command.execute();
  };
    document.getElementById('undo').onclick = function(){
    command.undo();
  };
};

setCommand( CreateCommand(Tv));

 摘自JavaScript设计模式与开发实践

posted on 2017-02-20 15:37  传说中的页面仔  阅读(152)  评论(0编辑  收藏  举报