使用 koa 避免 `this`
Avoiding `this` with koa
在 Koa 中,我们可以访问 Koa Context 而不使用预绑定 this?
例如:this
赋值给Koa Context:
app.use(function *(next) {
this.url;
})
但是有没有类似的东西:
app.use(function *(next, ctx) {
ctx.url;
})
为什么?假设我们使用箭头函数,this
不会是 koa 上下文:
app.use( function *( next ) {
console.log( this.url ); // logs: "/"
( () => console.log( this.url ) )(); // logs: "undefined"
});
我知道我们可以做到:
app.use( function *( next ) {
var ctx = this;
( () => console.log( ctx.url ) )(); // logs: "/"
});
和其他形式的绑定,但我想检查一下,根据设计,这是唯一的方法。
正在访问 this
Koa 运行每个中间件 this
绑定到上下文。访问请求和响应需要通过上下文,this
.
这绝对是设计使然。如果需要,将对上下文的引用存储在变量中:
var self = this
//or
var ctx = this
myArray.forEach( function( item ){
console.log( this.url )
}.bind( this ) )
Koa 的设计
我来解释一下another answer and the Koa FAQ。
Express 的外观和感觉与 "standard node way of doing things" 非常相似;它遵循 http
模块设置的示例。
另一方面,Koa 旨在取代 "the node way"。作者选择实现他自己的理想来处理请求和中间件。 Koa 在 this.request
和 this.response
中公开了它自己的请求和响应版本,在 this.req
和 this.res
中保留了原始节点 req
和 res
, 分别.
这些例子应该突出不同的心态。
Express 方法非常基于操作。
app.use( function( req, res ){
//SEND the response
res.send( 'some text' )
})
Koa 方法论非常"fact based"。
app.use( function*( next ){
//The response IS this
this.body = 'some text'
})
因此,Koa 似乎没有将 req
和 res
传递给函数,而是将它们作为请求的属性(或 "facts")公开。
新答案:
现在可以在 koa v2 中使用。
旧答案:
这不可能。中间件通过 thunks
(单参数函数)提供给应用程序,由 co.
提供
截至撰写本文时(2015 年 4 月),co 中的 thunk 已弃用。所以 Koa 是留在他们身边还是搬到 promises 还不得而知。我的 2p,来自其他函数式语言,thunks(和绑定上下文)阻碍了表达能力……也许我错了,但是箭头函数就是一个例子
在 Koa 中,我们可以访问 Koa Context 而不使用预绑定 this?
例如:this
赋值给Koa Context:
app.use(function *(next) {
this.url;
})
但是有没有类似的东西:
app.use(function *(next, ctx) {
ctx.url;
})
为什么?假设我们使用箭头函数,this
不会是 koa 上下文:
app.use( function *( next ) {
console.log( this.url ); // logs: "/"
( () => console.log( this.url ) )(); // logs: "undefined"
});
我知道我们可以做到:
app.use( function *( next ) {
var ctx = this;
( () => console.log( ctx.url ) )(); // logs: "/"
});
和其他形式的绑定,但我想检查一下,根据设计,这是唯一的方法。
正在访问 this
Koa 运行每个中间件 this
绑定到上下文。访问请求和响应需要通过上下文,this
.
这绝对是设计使然。如果需要,将对上下文的引用存储在变量中:
var self = this
//or
var ctx = this
myArray.forEach( function( item ){
console.log( this.url )
}.bind( this ) )
Koa 的设计
我来解释一下another answer and the Koa FAQ。
Express 的外观和感觉与 "standard node way of doing things" 非常相似;它遵循 http
模块设置的示例。
另一方面,Koa 旨在取代 "the node way"。作者选择实现他自己的理想来处理请求和中间件。 Koa 在 this.request
和 this.response
中公开了它自己的请求和响应版本,在 this.req
和 this.res
中保留了原始节点 req
和 res
, 分别.
这些例子应该突出不同的心态。
Express 方法非常基于操作。
app.use( function( req, res ){
//SEND the response
res.send( 'some text' )
})
Koa 方法论非常"fact based"。
app.use( function*( next ){
//The response IS this
this.body = 'some text'
})
因此,Koa 似乎没有将 req
和 res
传递给函数,而是将它们作为请求的属性(或 "facts")公开。
新答案:
现在可以在 koa v2 中使用。
旧答案:
这不可能。中间件通过 thunks
(单参数函数)提供给应用程序,由 co.
截至撰写本文时(2015 年 4 月),co 中的 thunk 已弃用。所以 Koa 是留在他们身边还是搬到 promises 还不得而知。我的 2p,来自其他函数式语言,thunks(和绑定上下文)阻碍了表达能力……也许我错了,但是箭头函数就是一个例子