美文网首页js
闭包实现命令模式

闭包实现命令模式

作者: u14e | 来源:发表于2017-02-23 12:26 被阅读8次

    面向对象版本:预先植入的命令接收者被当成对象的属性保存起来

    var Tv = {
        open: function() {
            console.log('open tv');
        },
        close: function() {
            console.log('close tv');
        }
    };
    
    var OpenTvCommand = function(receiver) {
        this.receiver = receiver;
    }
    
    OpenTvCommand.prototype.excute = function() {
        this.receiver.open();
    }
    
    OpenTvCommand.prototype.undo = function() {
        this.receiver.close();
    }
    
    var setCommand = function(command) {
        document.querySelector('#excute').onclick = function() {
            command.excute();
        };
        document.querySelector('#undo').onclick = function() {
            command.undo();
        };
    };
    
    setCommand(new OpenTvCommand(Tv));
    

    闭包版本:命令接收者被封闭在闭包形成的环境中

    var Tv = {
        open: function() {
            console.log('open tv');
        },
        close: function() {
            console.log('close tv');
        }
    };
    
    var createCommand = function(receiver) {
        var excute = function() {
            receiver.open();
        };
        var undo = function() {
            receiver.close();
        };
        return {
            excute: excute,
            undo: undo,
        };
    }
    
    var setCommand = function(command) {
        document.querySelector('#excute').onclick = function() {
            command.excute();
        };
        document.querySelector('#undo').onclick = function() {
            command.undo();
        };
    };
    
    setCommand(createCommand(Tv));
    

    相关文章

      网友评论

        本文标题:闭包实现命令模式

        本文链接:https://www.haomeiwen.com/subject/ajxbwttx.html