簡體   English   中英

如何在構造函數中調用函數

[英]How to call a function inside constructor

我有以下課程:

class QuestionService {
   static $inject = [
      "$interval",
      "$http",
      "$state"
   ];
   constructor(
      private $interval,
      private $http: ng.IHttpService,
      private $state
   ) {

      $interval(function () {
         this.putTestQuestionResponses()  // <-- error here 
                                          // this.putTestQuestionResponse
                                          // is not a function
      }, 5 * 1000);
   }

   putTestQuestionResponses = () => {
      // do something
   };
}

我想要做的是在上面的 $interval 函數中調用 putTestQuestionResponses() 。

我正在嘗試做的可能嗎? 有人可以讓我知道如何做到這一點嗎?

在這種情況下,我們需要箭頭函數,它將為我們保留上下文:

// instead of this
//$interval(function () { // this will be ... not expected
// we need arrow function
$interval(() => {         // arrow functions keep 'this' related to local context
     this.putTestQuestionResponses() 
}, 5 * 1000);

請參閱此了解更多信息:

TypeScript 箭頭函數教程

或在這里:

Basarat 的箭頭函數

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM