Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm increasingly a fan of local named functions in JS, vs. pulling callbacks entirely out of scope. An example:

    function compile(filename, ready) {
      return fs.readFile(filename, make_fn)

      function make_fn(err, data) {
        if(err) return ready(err)

        ready(null, new Function(data))
      }
    }
Which neatly addresses the desire to retain closures, while avoiding unnecessary nesting.

Also, whenever possible, I like to nix callbacks by using Function#bind:

    res.on('data', accum.push.bind(accum))

    // vs:
    res.on('data', function(data) { accum.push(data) })


I tend to favor one of these for clarity:

    Array.prototype.push.bind(accum)
    [].push.bind(accum)
(i realize the latter is wasteful, but arrays are so cheap that you wouldn't notice unless in a hot loop)


> Also, whenever possible, I like to nix callbacks by using Function#bind:

There's one (and only one) non-DOM jquery method I enjoy for that sort of things, because it avoids repetition: $.proxy(Object, String)

    accum.push.bind(accum)
becomes

    $.proxy(accum, 'push')
I think it spells out the intent better than the bind dance.

Of course, things would still be better if javascript just bound method on instance prototype lookup.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

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

Search: