![](/img/trans.png)
[英]Newly created objects call to constructor undefined if constructor is inside another function
[英]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);
請參閱此了解更多信息:
或在這里:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.