express中间件模拟实现

本文简单记录了作者尝试模拟实现Express中间件的过程,虽然尚未深入研究官方源码,但分享了个人的实现思路。后续计划对比源码,探讨可能的实现差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

没啥太多东西,记录下自己实现的思路,还没看源码。之后有机会看下源码比较下实现的差异。

var App = {
    index: 0,
    functionList:[],
    callback (ctx) {
        console.log(ctx.name);
    },
    use (middleware) {
        this.functionList.push(middleware);
    },
    go (ctx = {})  {
        let _this = this;
        let next = ()=>{
            if(_this.index< _this.functionList.length){
                _this.index = _this.index+1;
                _this.functionList[_this.index-1](ctx,next);
            }else{
                _this.callback(ctx);
            }
        };
        next();
    }
};

App.use(function (ctx, next) {
    ctx.name = 'hello';
    next();
});

App.use(function (ctx, next) {
    ctx.name += ' world';
    next();
});

App.go();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值