Created
July 28, 2014 15:26
-
-
Save davidnormo/c8cd3e4c4fce3186e46e to your computer and use it in GitHub Desktop.
Javascript Closures
This file contains 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
/** | |
* Be careful of closure behaviour, it might not give you values you expect! | |
* For example when you have timeouts or event listeners. | |
*/ | |
(function(){ | |
var i = 0, | |
arr = ['a','b','c','d'], | |
doSomething = function(localKey){ | |
console.log('i:', i); | |
console.log('localKey:', localKey); | |
}; | |
arr.forEach(function(value, key){ | |
i = key; | |
setTimeout(function(){ | |
console.log('key:', key); | |
doSomething(key); | |
}, 1000); | |
}); | |
})(); | |
/* Output | |
key: 0 | |
i: 3 | |
localKey: 0 | |
key: 1 | |
i: 3 | |
localKey: 1 | |
key: 2 | |
i: 3 | |
localKey: 2 | |
key: 3 | |
i: 3 | |
localKey: 3 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment