0009. 在 Controller 中获取上下文对象的两种方式
1. 💻 demos.1 - 在 Controller 中获取上下文对象的两种方式
- 通过
this.ctx
获取上下文对象 - 通过注入的参数
ctx
获取上下文对象
js
const { Controller } = require('egg')
class HomeController extends Controller {
async index(ctx) {
console.log(ctx === this.ctx) // => true
this.ctx.body = 'hi, egg'
}
}
module.exports = HomeController
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
js
const { Controller } = require('egg')
class HomeController extends Controller {
async index() {
const { ctx } = this
this.ctx.body = 'hi, egg'
}
}
module.exports = HomeController
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
- 推荐
this.ctx
- 上述两种方式获取到的上下文对象是一样的,从官方文档中提供的示例来看,通过
this.ctx
获取上下文对象是更加常见的写法。 - 在每个 Action 的第一行就是
const { ctx } = this
,将上下文对象从this
中解构出来。
- 上述两种方式获取到的上下文对象是一样的,从官方文档中提供的示例来看,通过