如何从子上下文访问类属性

How to access class properties from child context

本文关键字:访问 属性 上下文      更新时间:2023-09-26

当我需要从不同的作用域内访问类属性(或方法)时,我必须将其分配给函数作用域内的变量。

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;
        });
    }
}