5.extend的详细用法

一、重点

官网: https://eggjs.org/zh-cn/basics/extend.html

可扩展

Application
Context
Request
Response
Helper

需注意要在app下新建目录extend文件夹,根据官网创建对应的文件

application.js 、context.js 、 request.js 、response.js、 helper.js

二、application的扩展和使用

1.扩展

@file(application.js)

/*
    外部可以通过 this.app.foo() 来调用
*/
module.exports = {
    foo(params) {
        console.log('extend-app: 我是扩展方法');
    }
}

2.使用

Controller,Middleware,Helper,Service 中都可以通过 this.app来调用。

class HomeController extends Controller {
    async index() {
        // extend-application
        this.app.foo();  
        await this.ctx.render('home');
    }
}

二、context的扩展和使用

1.扩展

@file(context.js)

module.exports = {
    // this 就是 ctx 对象,在其中可以调用 ctx 上的其他方法,或访问属性
    getHost() {
        let host = this.request.header.host;
        console.log('extend-ctx: ', host);
        return host;
    }
}

2.使用

1. middleware 中 this 就是 ctx,例如 this.cookies.get('foo')。
2. controller 有两种写法,类的写法通过 this.ctx,方法的写法直接通过 ctx 入参。
3. helper,service 中的 this 指向 helper,service 对象本身,使用 this.ctx 访问 context 对象,例如 this.ctx.cookies.get('foo')。

例子:controller使用方式

class HomeController extends Controller {
    async index() {
        // extend-application
        this.app.foo();  
        await this.ctx.render('home');
    }
}

三、helper的扩展和使用

1.扩展

@file(application.js)

module.exports = {
    formatDate(date) {
        let time = '2012';
        console.log('time: ', time);
        return time
    }
}

2.使用

1.controller、service中使用

使用方法: this.ctx.helper.fn()

class HomeController extends Controller {
    async index() {        
        this.ctx.helper.formatDate(1453426595000);
    }
}

2.html中使用

使用:helper.fn()

<span><%=helper.formatDate(list[i].dateline)%></span>

四、request的扩展和使用

1.扩展

/*
    外部使用方式:this.ctx.request.fn()
*/
module.exports = {
    rfn(){
        console.log('我是extend-request的方法');
    }
}

2.使用

// controller、service中的使用方法
this.ctx.request.rfn();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值