zoukankan      html  css  js  c++  java
  • 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) ;
    最后温馨提示不要忘了清除定时器哦!
     
  • 相关阅读:
    20140710 sequence 前缀和
    20140709 testC 数学题
    20140708 testA 组合数学
    20140708 testB DP 组合数学
    Sad :(
    已经是一个废人了……
    Game Theory
    HDU Math Problems
    2-sat问题
    并查集
  • 原文地址:https://www.cnblogs.com/sunyuweb/p/9269481.html
Copyright © 2011-2022 走看看