在原生nodejs中,在监听响应的时候我们需要不断的去判断url,来响应不同的处理方式,这就会造成代码的很难去维护,
在express总就采用了中键的设计角度去思考,其中利用了next递归方式去调用,而this.cache相当于代理作用保存了所有中间键的方法.设计非常巧妙
function Middle(){ this.cache=[]; } Middle.prototype.use=function(fn){ if(typeof fn!="function"){ console.error("你传入的不是一个方法") } this.cache.push(fn); } Middle.prototype.next=function(){ if(this.middles.length==0||!this.middles){ return } var fn=this.middles.shift(); fn.call(this,this.next.bind(this)); } Middle.prototype.commit=function(){ this.middles=this.cache.slice(); this.next() } var middle=new Middle(); middle.use(function(next){ console.log(1); next(); }) middle.use(function(next){ console.log(2); next(); }) middle.use(function(next){ console.log(3); }) middle.use(function(next){ console.log(4); next(); }) middle.commit() middle.commit()