繁体   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