Created
April 22, 2015 03:43
-
-
Save chochos/1a89a83edde01df50bfe to your computer and use it in GitHub Desktop.
Go home, JavaScript, you're drunk...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); |
Author
Author
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.
Closure FTW ... http://plnkr.co/edit/IuTI4O2GMPEZtEY2zHbc?p=info
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
Just by reading the code, you can guess that it should print
meta3 times, thenfuncion. Right? Wrong. It's a stack overflow, and I'm not even sure why; it seems theitemvariable 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
itemis captured.Very intuitive, isn't it?