vue中使用定时器时this指向


箭头函数中的this指向是固定不变(定义函数时的指向),在vue中指向vue;
普通函数中的this指向是变化的(使用函数时的指向),谁调用的指向谁。
 
箭头函数:
1 let timerOne = setInterval(() => { 2     console.log(this);// vue
3 }, 1000); 4 let timerTwo = setInteval(function () { 5     console.log(this); // window,因为setInterval()函数是window对象的函数
6 }, 1000);
打印结果:
 
1 let timer = setInterval(() => { 2   this.myFunc(); 3 },1000); 4 myFunc(){ 5   console.log('sunyu is handsome !'); 6 }
不用箭头函数也可以搞定:
1 myFunc(){ 2   console.log(vm.name);// name为已经在created中声明的变量
3 }; 4 let  vm = this; 5 let timer = setInteval(function () { 6        myFunc(); 7 }, 1000) ;

 

最后温馨提示不要忘了清除定时器哦!
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM