下面这行代码仔细一想,和把业务逻辑抽离成方法,而后一个一个掉方法本质是同样的,可是区别在于咱们在中间件注册的方法不该该是业务逻辑,而应该是脱离于业务逻辑提供的一种适用于大多数场景的一个方法,她所提供的功能应该具备单一性 普适性javascript
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();