标签:无法 编写 结束 时间 push this his 模式 业务逻辑
当我们在编写业务代码时候,我们无法避免有些业务逻辑复杂而导致业务代码写得又长又乱,如果再加上时间紧凑情况下写出来的代码估计会更让人抓狂。以至于我们一直在寻求更好的架构设计和更好的代码设计,这是一个没有终点的求知之路,但是在这条路上会越走越好。
function Middleware(){
                this.cache = [];
            }
            Middleware.prototype.use = function(fn){
                if(typeof fn !== ‘function‘){
                    throw ‘middleware must be a function‘;
                }
                this.cache.push(fn);
                return this;
            }
            Middleware.prototype.next = function(){
                if(this.middlewares && this.middlewares.length > 0 ){
                    var ware = this.middlewares.shift();
                    ware.call(this, this.next.bind(this));
                }
            }
            Middleware.prototype.handleRequest = function(){//执行请求
                this.middlewares = this.cache.map(function(fn){//复制
                    return fn;
                });
                this.next();
            }
            var middleware = new Middleware();
            middleware.use(function(next){
                console.log(1);
                next();
                console.log(‘1结束‘);
            });
            middleware.use(function(next){
                console.log(2);
                next();
                console.log(‘2结束‘);
            });
            middleware.use(function(next){
                console.log(3);
                console.log(‘3结束‘);
            });
            middleware.use(function(next){
            console.log(4);next();console.log(‘4结束‘);
            });
            middleware.handleRequest();
标签:无法 编写 结束 时间 push this his 模式 业务逻辑
原文地址:https://www.cnblogs.com/mrzhu/p/10981971.html