1、使用js中的定时器(setInterval,setTimeout),很容易会遇到this指向的问题。
var name = 'window';
var obj = {
name: 'obj',
fn: function () {
var timer = null;
clearInterval(timer);
timer = setInterval(function () {
console.log(this.name); //window
}, 1000)
}
}
在这里,从this.name可以看出this的指向是window。
如果没有特殊指向,setInterval和setTimeout的回调函数中this的指向都是window。
这是因为JS的定时器方法是定义在window下的。
但是平时很多场景下,都需要修改this的指向。这里总结了几种:
2、最常用的方法:在外部函数中将this存为一个变量,回调函数中使用该变量,而不是直接使用this。
var name = 'window';
var obj = {
name: 'obj',
fn: function () {
var that = this;
var timer = null;
clearInterval(timer);
timer = setInterval(function () {
console.log(that.name); //obj
}, 1000)
}
}
3、使用es6的箭头函数:箭头函数的最大作用就是this指向。
箭头函数没有自己的this,它的this继承自外部函数的作用域。
(函数体内的this值,绑定的定义时所在的作用域的this)。
所以,在该例中,定时器回调函数中的this,是继承了fn的this。当然箭头函数也有兼容问题,要是兼容低版本ie,需要使用babel编译,并且引入es5-shim.js才可以。
var name = 'window';
var obj = { name: 'obj',
fn: function () {undefined
var timer = null;
clearInterval(timer);
timer = setInterval( () => {
undefined
console.log(this.name); //obj
}, 1000)
}
}
3、bind
let time=setInterval(function () {
this.second--;
if(this.second==0){
location.replace("./login.html")
}
}.bind(this),1000,1000)