Jef*_*eff 2 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.API.makeHttpCall().then(function(valueFromServer) {
// accessing via local variable
myClass.property = valueFromServer;
});
}
}
Run Code Online (Sandbox Code Playgroud)
对于每种方法,我都不需要这样做.还有另一种方法吗?
是的 - 使用箭头功能:
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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |