setTimeout中的变量表示它未定义,但在外部定义时 [英] Variable inside setTimeout says it is undefined, but when outside it is defined

查看:959
本文介绍了setTimeout中的变量表示它未定义,但在外部定义时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课了。我需要在超时内做一些http工作。我面临的问题是超时内的http变量一直说它是未定义的。

I have a class. I need to do some http work inside of a timeout. The problem I am faceing is the http variable inside the timeout keeps saying it is undefined.

export class MyClass {

    http:Http:

    constructor(private http:Http) {
        this.http = http;
    }

    sendFriendRequest(){

    this.http.post( ...//http variable is defined here
           setTimeout(function(){
               this.http.post(...  //http is not defined here
        }
   }
}


推荐答案

原因是setTimeout 中的回调函数处于不同的词汇环境。这就是为什么ES6 +函数可以使用 => 来定义。这样,函数中的代码与函数共享相同的范围。

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.

要解决此问题,您可以使用ES6 +语法,而不是函数(a,b,args){...} 你将使用(a,b,args)=> {...}

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(...)
});

或使用ES5语法:

var root = this;

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

希望这会有所帮助!

这篇关于setTimeout中的变量表示它未定义,但在外部定义时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆