Never use anonymous functions in JS
I think I've found the silver bullet for the evil stuff in JS: Never use anonymous functions!
You then no longer have to make closures or visit callback hell. And your code get easier to understand.
for(var i=0; i < texcture.length; i++) {
texcture[i].onload = function(i) {
pattern[i] = ctx.createPattern(texcture[i], 'repeat');
}
}
Witch will summon the evil closure: for(var i=0; i < texcture.length; i++) {
texcture[i].onload = (function(index) {
return function() {
pattern[index] = ctx.createPattern(texcture[index], 'repeat');
};
}
})(i);
But if you used my silver bullet: Avoid anonymous functions - the root of evil ... for(var i=0; i < texcture.length; i++) {
createPattern(i);
}
function createPattern(i) {
texcture[i].onload = function() {
pattern[i] = ctx.createPattern(texcture[i], 'repeat');
}
}Sure, if you're littering your code with anonymous functions at the top level, you have no idea what is executing when or why. But who does that?
How do you think naming a function, then calling it is any better, if you just littered your function calls all over the place (assuming that is why you think this is a problem of course).