zoukankan      html  css  js  c++  java
  • 定时器里面的作用域问题

    /*
      各种运动
    */
    function Animation(){};
    
    
    Animation.prototype={

    /*
    匀速运动
    */ linear:
    function(obj,target){ obj.timer=null; clearInterval(obj.timer); var step=obj.offsetLeft<target?5:-5;//用位置来判断运动的方向 if(obj.offsetLeft!=target){ obj.timer=setInterval(function(){ var res=target-obj.offsetLeft;//核心好代码 当运动到指定位置的时候差值不会超过5 来作为停止运动的条件 if(Math.abs(res)<=Math.abs(step)){ obj.style.left=target+"px"; clearInterval(obj.timer); } else{ obj.style.left=obj.offsetLeft+step+"px"; } } ,1000/60); } }, /*
    循环往复运动
    */ loop:
    function(obj,target){ var timer=null; clearTimeout(timer); var fn=arguments.callee.bind(this);//绑定this指向 if(obj.offsetLeft==target){ this.linear(obj,0); } else if(obj.offsetLeft==0){ this.linear(obj,target); } /* 定时器的作用域是全局作用域 在里面调用的函数都是全局作用域下调用的 */ timer=setTimeout(function(){ fn(obj,target); },900); } }
    var animation=new Animation();


    刚开始我没有绑定fn的this指向的时候 一直报错
     

     我当时就想咋回事呢  明明函数是定义在Animation里面的  方法也是由它调用的  所以this应该指向的是Animation呀

    于是乎我就继续往下看  看打了

    奥,明白了  setTimeout 和 setInterval  

     一般都是这么写

      timer=setTimeout(function(){},1000/60);

     function 就是定时器函数的一个回掉函数

     是由定时器函数去执行的 所以 回调函数里面的this

    就是setInterval 里面的this

    而setInterval函数的调用者是window

    所以回调函数里面的this指的是window

    而linear是定义在Animation里面的  所以找不到函数  报错

    如果把fn函数的作用域绑定在Animation上 就没关系了

    var fn=arguments.callee.bind(this);
    当调用loop的时候 this指的就是Animation


    如果没明白 我再举一个简单的例子
    var obj={
    age:"17;
    }

    setInterval(function(){

    console.log(this.age);

    }.bind(obj),1000);

  • 相关阅读:
    开发细节
    html
    java学习
    Promise对象
    强制转换和隐式转换
    借助防抖解决输入框的非空校验
    setTimeout
    Symbol类型
    js API
    vue 使用mixin
  • 原文地址:https://www.cnblogs.com/liveoutfun/p/9309795.html
Copyright © 2011-2022 走看看