Reputation: 141
When I need to access the class properties (or methods) from within a different scope, I have to assign it to a variable from within the function scope.
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;
});
}
}
This is something I'd rather not have to do for every method. Is there another way to do this?
Upvotes: 2
Views: 115
Reputation: 22362
Yes there is - use arrow functions:
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;
});
}
}
Upvotes: 5