Scope problem in timer

Keywords: Javascript

/*
  All kinds of sports
*/
function Animation(){};


Animation.prototype={

/*
Uniform motion
*/ linear:
function(obj,target){ obj.timer=null; clearInterval(obj.timer); var step=obj.offsetLeft<target?5:-5;//Use position to judge the direction of motion if(obj.offsetLeft!=target){ obj.timer=setInterval(function(){ var res=target-obj.offsetLeft;//Core good code when moving to the designated position, the difference will not exceed 5 as a condition to stop the movement 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); } }, /*
Circular motion
*/ loop:
function(obj,target){ var timer=null; clearTimeout(timer); var fn=arguments.callee.bind(this);//binding this point if(obj.offsetLeft==target){ this.linear(obj,0); } else if(obj.offsetLeft==0){ this.linear(obj,target); } /* The scope of the timer is the global scope The functions called in it are all called in the global scope */ timer=setTimeout(function(){ fn(obj,target); },900); } }
var animation=new Animation();


I didn't bind at first fn Of this Always report an error when pointing

 

 

What did I think at that time? Clearly, the function is defined in Animation, and the method is also called by it. So this should point to Animation

So I went on to look down and fight

 

Oh, I see. setTimeout and setInterval

It's usually written like this

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

The scope of the common function in the closure is window

So if fn is executed under window, then this is window

And linear is defined in Animation, so no function error can be found

It doesn't matter if you bind the scope of fn function to Animation

var fn=arguments.callee.bind(this);
this refers to Animation when loop is called


If you don't understand, let me give you another simple example
var obj={
age:"17;
}

setInterval(function(){

console.log(this.age);

}.bind(obj),1000);

Posted by bambambanana on Sat, 15 Feb 2020 10:14:43 -0800