[英]How to access class method inside an anonymous function
I have an method in my JS class and in the callback of a Promise, I want it to call another class method.我的 JS class 中有一个方法,在 Promise 的回调中,我希望它调用另一个 class 方法。
class MyClass {
myClassMethod(arg1) {
// this method did get called
}
aSecondClassMethod() {
//...
}
methodWithPromise() {
var myClassMethod = this.myClassMethod;
let aPromise = methodReturnPromise();
aPromise.then(function (value) {
myClassMethod(value);
}
}
So I create a var calls myClassMethod
and set that to this.myClassMethod
.所以我创建了一个 var 调用
myClassMethod
并将其设置为this.myClassMethod
。 And when I debug the code, myClassMethod did get called in the then
callback of the Promise.当我调试代码时,myClassMethod 确实在 Promise 的
then
回调中被调用。
The problem I am having is when my myClassMethod()
calls other class method(), ie我遇到的问题是当我的
myClassMethod()
调用其他 class 方法() 时,即
myClassMethod(args) {
aSecondClassMethod();
}
I get error saying aSecondClassMethod
is undefined.我收到错误消息说
aSecondClassMethod
未定义。 I tried我试过了
myClassMethod(args) {
this.aSecondClassMethod();
}
But it gives me the same error.但它给了我同样的错误。 I think I can work around this by declaring a var for each of the class method that myClassMethod() calls.
我想我可以通过为 myClassMethod() 调用的每个 class 方法声明一个 var 来解决这个问题。
var aSecondClassMethod= this.aSecondClassMethod;
But that seem cumbersome to maintain the code going forward.但这对于继续维护代码似乎很麻烦。
I would like to know if there is a better way to do this.我想知道是否有更好的方法来做到这一点。
Use an arrow function, as it captures the this
value of the enclosing context.使用箭头 function,因为它捕获封闭上下文的
this
值。
aPromise.then(value => this.myClassMethod(value));
I would also recommend using the new () => {}
function notation for defining the class method that contains the promise. Without that (or an old school bind) this
will still be undefined
.我还建议使用新的
() => {}
function 符号来定义包含 promise 的 class 方法。如果没有它(或老式绑定) this
仍然是undefined
。
My usual style:我一贯的作风:
class MyClass {
myClassMethod = (value) => {
//something..
};
methodWithPromise = () => {
somePromise
.then((res) => {
this.myClassMethod(res);
})
.catch((err) => {
console.error(err);
return;
});
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.