//面向对象的方式 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设计模式与开发实践