Skip to content

Instantly share code, notes, and snippets.

@s-stude
Created July 2, 2014 10:59
Show Gist options
  • Save s-stude/90a12a0b392d63317b45 to your computer and use it in GitHub Desktop.
Save s-stude/90a12a0b392d63317b45 to your computer and use it in GitHub Desktop.
JavaScript "Сlosures" Craziness
// task to fix this: should output 4, 3, 2, 1, 0
this.index = 5;
while(index--){
code = window.setTimeout(function(){
console.log(this.index);
}.bind(this),500);
}
// 1
this.index = 5;
while(index--){
code = window.setTimeout(console.log.bind(console, this.index),500);
}
// 2
this.index = 5;
while(index--){
setTimeout(function(index){
console.log(index);
}.bind(this, index),500);
}
// 3
this.index = 5;
while(index--){
code = window.setTimeout((function(idx){
return function() {
console.log(idx);
}
})(this.index),500);
}
// 4
this.index = 5;
while(index--) with({ index: index }) {
code = window.setTimeout(function(){
console.log(index);
}.bind(this),500);
}
// 5
this.index = 5;
while(index--) with({ index: index }) {
code = window.setTimeout("console.log("+index+");",500);
}
// 6
this.index = 5;
while(index--) with({ index: index }) {
code = eval('setTimeout("console.log("+index+");",500)');
}
// 7
this.a = 5;
while(a--) with({ b: a }) {
code = eval('setTimeout("console.log("+b+");",500)');
}
// 8
try{
while(a = (++this.a ? (--this.a - 1) : "5")) with({ b: a }) {
code = eval('setTimeout("console.log("+b+");",500)');
!~(b) && new Error;
}
} catch(e){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment