typescript或者javascript设置定时器时关于this的问题

在设置定时器时,setInterval和setTimeout的回调函数中this的指向都是window。这是因为定时器方法是在window下定义的。

this.timeInterval = setInterval(function () {
    console.log(this);
}, 1000);

 

 

 

可以通过一下方式改变this的指向:

1.在函数内定时器前重新定义需要用的变量,回调函数中使用该变量。

this.timeInterval = setInterval(function () {
    let array = this.selectArray;
    console.log(array);
 }, 1000)

 

 2.使用es6的箭头函数

this.timeInterval = setInterval(()=>{
    console.log(this);
}, 1000);

 

 3.使用bind()方法

this.timeInterval = setInterval(function () {
  console.log(this.selectArray);
}.bind(this), 1000);

 

 

 

posted @ 2021-01-18 11:27  '--'  阅读(196)  评论(0)    收藏  举报