用koa避免`this`

Ros*_*oss 3 koa

在兴亚,我们可以访问兴亚背景下不使用预先绑定这个

例如:this被分配给Koa上下文:

app.use(function *(next) {
    this.url;
})
Run Code Online (Sandbox Code Playgroud)

但是有类似的东西:

app.use(function *(next, ctx) {
    ctx.url;
})
Run Code Online (Sandbox Code Playgroud)

为什么?假设我们使用箭头函数,this不会是koa上下文:

app.use( function *( next ) {

    console.log( this.url ); // logs: "/"

    ( () => console.log( this.url ) )(); // logs: "undefined"

});
Run Code Online (Sandbox Code Playgroud)

我知道我们可以这样做:

app.use( function *( next ) {
    var ctx = this;
    ( () => console.log( ctx.url ) )(); // logs: "/"
});
Run Code Online (Sandbox Code Playgroud)

和其他形式的绑定,但我想检查,通过设计,这是唯一的方法.

Jos*_*lik 5

访问 this

Koa运行每个中间件并this绑定到Context.访问请求和响应需要通过上下文,this.

这绝对是设计上的.如果需要,在变量中存储对上下文的引用:

var self = this
//or
var ctx = this
Run Code Online (Sandbox Code Playgroud)

或者使用Function.prototype.bind:

myArray.forEach( function( item ){
    console.log( this.url )
}.bind( this ) )
Run Code Online (Sandbox Code Playgroud)

Koa的设计

我会解释另一个答案Koa FAQ.

Express的外观和感觉非常像"标准节点做事方式"; 它遵循http模块设置的示例.

另一方面,Koa意在取代"节点方式".作者选择实现自己的处理请求和中间件的理想.兴亚暴露出它在请求和响应的自己的版本this.request,并this.response保留原有节点reqresthis.reqthis.res分别.

这些例子应该将不同的思维模式集中在一起.

Express方法基于行动.

app.use( function( req, res ){
    //SEND the response
    res.send( 'some text' )
})
Run Code Online (Sandbox Code Playgroud)

Koa方法非常"基于事实".

app.use( function*( next ){
    //The response IS this
    this.body = 'some text'
})
Run Code Online (Sandbox Code Playgroud)

如此看来,强似reqres以功能以程序的方式,兴亚将它们公开为属性(或"事实")的要求.