2017-02-24 34 views
1

如何在从异步方法调用时引用类实例。在es2017中,从异步方法进行访问时'this'未定义

class Senders { 
    callSendAPI() { 
    //Some code here 
    } 
    sendText() { 
    this.callSendAPI(); 
    } 
    async sendCards() { 
    var dbpromise = await db.call(); 
    console.log('this= ', this); 
    this.callSendAPI(); 
    } 
} 
export {Senders}; 

此=未定义

+0

你使用巴贝尔还是别的什么? –

+0

如果这样听起来像是一个在该转换器讨厌的bug。 –

+7

如何调用sendCards()?你需要显示那个代码,因为这决定了sendCards()内'this'的值。问题可能出现在您未显示的调用代码中。我会冒险猜测你传递'obj.sendCards'作为回调,这就是为什么它不起作用。如果我的猜测是正确的,请参阅[如何让回调在类范围中使用“this”](http://stackoverflow.com/questions/15048775/how-to-get-callback-to-work-with-this -in-类作用域/ 15048802#15048802)。 – jfriend00

回答

1

的问题是,要么你使用任何transpiler,如果你使用一个,或给它被调用的方式功能的情况下。我在NodeJS v7.x中运行了以下代码片段,它工作得很好,显示了这个值是发件人的类实例。

class Senders { 
 
    async sendCards() { 
 
    console.log('this= ', this); 
 
    } 
 
} 
 

 
new Senders().sendCards();

如果你确定这是不是你transpiler,然后尝试使用bindcall/apply时要调用的函数控制执行上下文。