下面這行代碼仔細一想,和把業務邏輯抽離成方法,而後一個一個掉方法本質是同樣的,可是區別在於咱們在中間件註冊的方法不該該是業務邏輯,而應該是脫離於業務邏輯提供的一種適用於大多數場景的一個方法,她所提供的功能應該具備單一性 普適性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();