"this" 当函数在链中作为参数传递时未定义
"this" is undefined when function is passed as argument in chain
我的问题的简单例子
考虑以下情况,我在 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
.
调用它的
问题出在这里:
this.a().then(this.b)
因为 this.b
检索到的结果函数与 this
解除绑定(您实际上并没有按照问题中所述的方式调用它)。
您可以通过使用箭头方法来保留范围,以与其余代码一致的方式解决它:
this.a().then(obj => this.b(obj))
或者您可以使用 .bind
来获得类似的结果:
this.a().then(this.b.bind(this))
我的问题的简单例子
考虑以下情况,我在 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
.
问题出在这里:
this.a().then(this.b)
因为 this.b
检索到的结果函数与 this
解除绑定(您实际上并没有按照问题中所述的方式调用它)。
您可以通过使用箭头方法来保留范围,以与其余代码一致的方式解决它:
this.a().then(obj => this.b(obj))
或者您可以使用 .bind
来获得类似的结果:
this.a().then(this.b.bind(this))