首页 > 其他 > 详细

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

时间:2021-01-21 09:29:40      阅读:24      评论:0      收藏:0      [点我收藏+]

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!

 

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

原文:https://www.cnblogs.com/chucklu/p/14305942.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!