setInterval中this的指向问题
最近在学习vue,其中有个跑马灯的案例,用到了
setInterval,当我用this的时候发生了错误,提示slice is not a function
var vm = new Vue({
el: '#app',
data: {
msg: '醉里寻他千百度,蓦然回首,那人却在灯火阑珊处 ',
timer: null
},
methods: {
move: function() {
if(this.timer != null) {
return;
}
this.timer = setInterval(function() {
console.log(this) // 这里在控制台输出的是window
var start = this.msg.slice(0, 1);
var end = this.msg.slice(1);
this.msg = end + start;
}, 400)
},
stop: function() {
clearInterval(this.timer);
this.timer = null;
}
}
})
总结: 在定时器当中的
this一般都是指向window的,我们可以提前保存一下this,var that = this,或者使用es6中的箭头函数来解决这个问题,还有一个方式不太常用就是setInterval中可以传入第三个参数this。