【发布时间】:2015-05-21 11:25:59
【问题描述】:
在 Koa 中,我们可以在不使用预先绑定的 this 的情况下访问 Koa Context 吗?
例如:this 分配给 Koa 上下文:
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: "/"
});
和其他形式的绑定,但我想检查一下,按照设计,这是唯一的方法。
【问题讨论】:
-
使用
.bind(this)怎么样?这可以与胖箭头一起使用吗?另外,胖箭头的目的不是保护环境范围吗?也许您使用不正确? -
你为什么要这样做?
-
做什么?抱歉不明白q。
-
请注意,v2.0 提供了上下文作为参数
-
你的前提是错误的。胖箭头函数不会劫持
this。这是他们的主要特点之一。
标签: koa