
Closures explained with JavaScript - skilldrick
http://skilldrick.co.uk/2011/04/closures-explained-with-javascript/
======
happy4crazy
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;
      }
      
      f();
    

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
        foo
      end
    
      f # => NameError: undefined local variable or method `foo' ...
    

And then you say, er, Ruby does closures too:

    
    
      foo = 0
      
      define_singleton_method :f do
        foo
      end
      
      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.

~~~
skilldrick
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.

~~~
happy4crazy
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...](http://www.amazon.com/Metaprogramming-Ruby-Program-Like-
Pros/dp/1934356476/ref=sr_1_1?ie=UTF8&qid=1303494088&sr=8-1)

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

~~~
skilldrick
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.

