Javascript 如何从子上下文访问类属性
当我需要从不同范围内访问类属性(或方法)时,我必须从函数范围内将其分配给变量Javascript 如何从子上下文访问类属性,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,当我需要从不同范围内访问类属性(或方法)时,我必须从函数范围内将其分配给变量 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
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;
});
}
}
使用箭头函数,它将保留
this
this.API.makeHttpCall.call(this)的值。然后(…