4 ms·
Lets say you have a bunch of textures and want to create a pattern for each of them. Most people would do it like this: for(var i=0; i < texcture.length; i++
by z3t4 12y ago
Lets say you have a bunch of textures and want to create a pattern for each of them.
Most people would do it like this:
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');
}
}