Skip to content

Instantly share code, notes, and snippets.

@chochos
Created April 22, 2015 03:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chochos/1a89a83edde01df50bfe to your computer and use it in GitHub Desktop.
Save chochos/1a89a83edde01df50bfe to your computer and use it in GitHub Desktop.
Go home, JavaScript, you're drunk...
function meta(f) {
console.log("en meta");
f();
}
var lista=[meta,meta,meta];
var fun=function() {
console.log("funcion");
}
for(var i=0;i<lista.length;i++) {
var item=lista[i];
//(function(){
var tmp=fun;
fun=function() {
item(tmp);
}
//}());
}
fun();
@chochos
Copy link
Author

chochos commented Apr 22, 2015

Just by reading the code, you can guess that it should print meta 3 times, then funcion. Right? Wrong. It's a stack overflow, and I'm not even sure why; it seems the item variable is not really captured in the function created inside the loop, so it ends up pointing to itself.

To fix it, uncomment lines 11 and 16. Now you have a separate scope, where item is captured.

Very intuitive, isn't it?

@chochos
Copy link
Author

chochos commented Apr 22, 2015

OK so changing line 14 to meta(tmp) still results in stack overflow. So apparently the problem is with tmp; if you uncomment lines 11 and 16 and then swap lines 11 and 12 so that tmp is declared outside the anon function, stack overflow happens again.

@mdrmtz
Copy link

mdrmtz commented Apr 22, 2015

@jeduan
Copy link

jeduan commented Apr 28, 2015

function meta (f) {
  console.log('en meta')
  f()
}
var lista = [meta, meta, meta]
var fun = function () {
  console.log('funcion')
}
lista.forEach(function (item) {
  var tmp = fun
  fun = function () {
    item(tmp)
  }
})
fun()
$ node index.js
en meta
en meta
en meta
funcion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment