Hacker News new | past | comments | ask | show | jobs | submit login

What you describe is the moment someone would usually go from PITA to Ninja! From programming sequential to async using functions. The WTF code:

  for(var i=0; i < textures.length; i++) {
    textures[i].onload = function (i) {
      pattern[i] = ctx.createPattern(textures[i], 'repeat');
    }
  }
The enlightenment:

  for(var i=0; i < textures.length; i++) {
    createPattern(i);
  }

  function createPattern(i) {
    textures[i].onload = function() {
      pattern[i] = ctx.createPattern(textures[i], 'repeat');
    }
  }
In JavaScript you can now however replace var with let and it will be block scoped and the WTF code will work. It's sad though as people learning JavaScript now will not get the beauty of it and will be stuck in callback hell. Function scope in JavaScript pushes you in the right direction. It's like instead of teaching people how to fly, we give them roads so they can walk, like they are used to.



It's way more than just async callbacks. For example, you may be using a lazy sequence abstraction, with high-order functions like the usual map/filter/reduce, but with a deferred implementation (i.e. they're only applied, and functions passed as arguments are evaluated, when the next item is read from the sequence). If you create such deferred sequences inside a loop, they will again capture the mutated counter.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: