一般来说,谁调用了函数,函数内部的this就指向谁。
在这里,setInterval的调用对象是window,所以函数内部的this指代的是window。
而msg属性绑定的是vue实例,所以要用_this。
methods: {
start: function () {
let _this = this;
this.timer = setInterval(function() {
let start = _this.msg.substring(0, 1);
let end = _this.msg.substring(1);
_this.msg = end + start;
}, 500)
},
}
箭头函数指代指代的this取决于外部环境,而不取决于谁调用了它。
外部的this指代的是实例,所以这里可以直接使用this
methods: {
start: function () {
this.timer = setInterval(() => {
let start = this.msg.substring(0, 1);
let end = this.msg.substring(1);
this.msg = end + start;
}, 500)
},
}