如何在构造函数中调用函数

时间:2015-10-04 14:36:22

标签: javascript typescript

我有以下课程:

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()。

我正在尝试做什么?有人能告诉我怎么做吗?

1 个答案:

答案 0 :(得分:2)

在这种情况下,我们需要箭头功能,它将为我们保留上下文:

// 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 Arrow Function Tutorial

或在这里:

<{3}}

Arrow Functions