【发布时间】:2016-02-06 04:23:47
【问题描述】:
我的问题的简单示例
考虑以下情况,我在c 的承诺链中使用了一些函数(a 和 b):
class SomeClass {
constructor(){
this.v1 = 1;
this.v2 = 2;
}
a() {
return new Promise((resolve, reject) => {
console.log('a', this.v1); // Do something with `this`
resolve();
});
}
b() {
return new Promise((resolve, reject) => {
console.log('b', this.v2); // Do something with `this`
resolve();
});
}
c() {
return this.a().then(this.b); // passing b as argument
}
}
当我调用c 并运行承诺链时,this 在b 中未定义。
const sc = new SomeClass();
sc.c().then(() =>{
console.log('done')
}).catch((error) => {
console.log('error', error);
});
输出:
a 1
error [TypeError: Cannot read property 'v2' of undefined]
我知道箭头函数继承了外部this,但我不确定为什么它是未定义的,因为我是从c 调用它。
【问题讨论】:
标签: javascript ecmascript-6 babeljs