Variable inside setTimeout says it is undefined, but when outside it is defined [duplicate]

Variable inside setTimeout says it is undefined, but when outside it is defined [duplicate]

The reason for this is that the callback function inside setTimeout is in a different lexical environment. This is why in ES6+ functions can be defined using =>. This is so that the code within a function shares the same scope as the function.

To fix this, you can either use ES6+ syntax, where instead of function(a,b,args){...} you would use (a,b,args) => {...}:

setTimeout(() => {
  this.http.post(...);
});

or with ES5 syntax:

var root = this;

setTimeout(function(){
    root.http.post(...);
});

Hope this helps!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章