当我需要在不同范围内访问类属性(或方法)时,必须将其分配给函数范围内的变量。
class MyClass {
constructor(API) {
this.API = API;
this.property = 'value';
}
myMethod() {
var myClass = this; // I have to assign the class to a local variable
this.API.makeHttpCall().then(function(valueFromServer) {
// accessing via local variable
myClass.property = valueFromServer;
});
}
}
我宁愿不必对每种方法都执行此操作。还有另一种方法吗?
最佳答案
是的,有-使用箭头功能:
class MyClass
{
private API;
private property;
constructor(API)
{
this.API = API;
this.property = 'value';
}
public myMethod()
{
API.makeHttpCall().then((valueFromServer) =>
{
// accessing via local variable
this.property = valueFromServer;
});
}
}