Skip to content

Instantly share code, notes, and snippets.

@craigphicks
Created July 10, 2019 21:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigphicks/e826e6351e213b9794482d35ef6d521f to your computer and use it in GitHub Desktop.
Save craigphicks/e826e6351e213b9794482d35ef6d521f to your computer and use it in GitHub Desktop.
testing javascript setTimeout args, bind, scope.
x=10;
function test(){
  var x=20;
  var obj = {x:30};
  function logargs(t,arg1,arg2,arg3,arg4) { 
    console.log(`(${t}) this.x=${this.x},x=${x},obj.x=${obj.x},${arg1},${arg2},${arg3},${arg4.x}`); 
  }
  logargs("A",this.x,x,obj.x,obj);
  setTimeout(logargs,0,"B",this.x,x,obj.x,obj);
  setTimeout(logargs.bind(obj),0,"C", this.x, x,obj.x,obj);
  x+=1;
  obj.x+=1;
  this.x+=1;
}
test();
test();

results in

"(A) this.x=10,x=20,obj.x=30,10,20,30,30"
"(A) this.x=11,x=20,obj.x=30,11,20,30,30"
"(B) this.x=12,x=21,obj.x=31,10,20,30,31"
"(C) this.x=31,x=21,obj.x=31,10,20,30,31"
"(B) this.x=12,x=21,obj.x=31,11,20,30,31"
"(C) this.x=31,x=21,obj.x=31,11,20,30,31"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment