Hacker News new | past | comments | ask | show | jobs | submit login
Closures explained with JavaScript (skilldrick.co.uk)
4 points by skilldrick on Apr 22, 2011 | hide | past | favorite | 4 comments

Nice article :)

The thing that helped me understand closures was really thinking about why they're confusing for beginners.

For example, let's say you show the following code to someone who's never heard of closures, and ask them what it should do.

  var foo = 0;

  var f = function() {
    return foo;
The thing that's confusing to beginners here is that there is no right answer to this question, and yet by being asked the question, you feel like you should be able to intuit the "right" behavior. For example, the previous code returns 0, but the analogous code will break in Ruby:

  foo = 0
  def f

  f # => NameError: undefined local variable or method `foo' ...
And then you say, er, Ruby does closures too:

  foo = 0
  define_singleton_method :f do
  f # => 0
How to handle this situation is up to the programming language: it might break, or it might use dynamic scope, or it might use closures/lexical scope (any others?).

Closures are initially confusing not because they're a difficult topic, but because their entire existence hinges on a programming language design decision that you, as a beginner, know nothing about. You can't see it in the text of the program. I think that if you clarify up front that someone, back in the day, realized that it would be pretty cool if languages worked liked this, instead of like that, then it makes understanding closures a lot easier.

Thanks, and a really interesting perspective.

I find Ruby's rules on scope (and pretty much anything) pretty confusing. I really like the way Ruby does a lot of things, but it doesn't have simple rules like JS.

Metaprogramming Ruby [0] explains Ruby's handling of scope really well.

Also, you might enjoy a silly gem I wrote a while ago called ghost_attributes [1]. It uses closures to mimic attr_accessor. The funny thing about it is that your ghost attributes are completely inaccessible from outside the object, unlike normal instance variables, which are always reachable via things like instance_variable_get. Fun/weird stuff :)

[0] http://www.amazon.com/Metaprogramming-Ruby-Program-Like-Pros...

[1] https://github.com/happy4crazy/ghost_attributes

Crazy! Yeah, Metaprogramming Ruby is on my wishlist. I understand why the rules in Ruby are complicated - it's to make the common case simpler. But I still like the simplicity of JavaScript.

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