5

在 Koa 中,我可以通过以下方式访问第一个生成器函数中的 Koa 上下文this

app.use(function *(){
    this; // is the Context
}

但是,如果我屈服于另一个生成器函数,我将无法再通过它访问上下文this

app.use(function *(){
    yield myGenerator();
}

function* myGenerator() {
    this.request; // is undefined
}

我已经能够简单地将上下文传递给第二个生成器函数,但想知道是否有更简洁的方法来访问上下文。

有任何想法吗?

4

1 回答 1

12

如您所说,要么this作为参数传递:

app.use(function *(){
    yield myGenerator(this);
});

function *myGenerator(context) {
    context.request;
}

或使用apply()

app.use(function *(){
    yield myGenerator.apply(this);
});

function *myGenerator() {
    this.request;
}
于 2014-10-30T03:16:52.553 回答