JavaScript进阶设计模式系列——基础篇——闭包(5)--命令模式的两种实现方式

来源:互联网 发布:如何做好淘宝售后服务 编辑:程序博客网 时间:2024/06/07 00:26

在面向对象的世界中,过程和数据是一个经常被使用的表达方式。对象,通过方法的形式包含着过程,而闭包则是在过程中以环境的形式包含了数据,因此,只要是用面向对象思想实现的东西,基本上用闭包的思想也能实现。下面,咱们看一则实例,分别使用面向对象形式来实现的写法和使用闭包形式的写法。

面向对象的写法

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>commandpatern</title></head><body>    <button id="execute">click me !</button>    <button id="undo">click me !</button>    <script>        var Tv = {//电视机本身应该具有的方法            open: function() {                console.log('open TV !')            },            close : function(){                console.log('close TV !')            }        }        var OpenTvCommand = function(receiver){ //命令对象本身            this.receiver = receiver;        }        OpenTvCommand.prototype.execute = function () {            this.receiver.open();        }        OpenTvCommand.prototype.undo = function () {            this.receiver.close();        }        var setCommand = function (command) {//相当于要遥控器、命令的发出者            document.getElementById('execute').onclick = function () {                command.execute();            }            document.getElementById('undo').onclick = function () {                command.undo();            }        }        setCommand( new OpenTvCommand(Tv));    </script></body></html>

闭包方式的实现:

var Tv = {    open: function () {        console.log('open TV');    },    close: function () {        console.log('close TV');    }};var OpenTvCommand =function (receiver) {//此处不使用立即执行函数的方式,也不需要OpenTVCommand对象自己持有变量,因为receiver这个局部变量会被闭包环境包围,这个局部变量被延续了生命周期   // this.receiver = receiver;    var execute = function () {        receiver.open();    }    var undo = function () {        receiver.close();    }    return {        execute: execute,        undo: undo    }};var setCommond = function (command) {    document.getElementById('execute').onclick=function () {        command.execute();    }    document.getElementById('undo').onclick=function () {         command.undo();    }}setCommond(OpenTvCommand(Tv));//不需要new这个对象,因为OpenTVCommand返回一个对象
阅读全文
0 0
原创粉丝点击