Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从子上下文访问类属性_Javascript_Typescript_Ecmascript 6 - Fatal编程技术网

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)的值。然后(…