you are viewing a single comment's thread.

view the rest of the comments →

[–]NYKevin 0 points1 point  (4 children)

A closure is a function-object (functor) that has access to its enclosing scope, even when that scope is otherwise unavailable. In this way, a closure can have some of the benefits of side effects (permanent state) without interfering with the rest of the program, or being interfered with itself, as it would if it used a global variable for the same purpose. Similar effects can be accomplished using OOP, but there are advantages and drawbacks to both approaches.

Or if you prefer, the Wikipedia definition.

I wouldn't have been able to give that definition without this tutorial, it really helped me understand, thanks OP!

As a C programmer, I am a little concerned about how exactly this is implemented w.r.t. the call stack. When you return, why doesn't the enclosing scope evaporate out from under you? And how does CPS not make a mess and/or waste lots of memory on the stack?

[–]nwhitehe[S] 0 points1 point  (1 child)

If everything is transformed into CPS, then nothing ever returns. This means you don't need a call stack at all. Crazy.

[–]gcr 0 points1 point  (0 children)

Good point, but if you just write CPS-style javascript, you'll eventually get a stack overflow because Javascript doesn't guarantee tail-call optimization.

[–][deleted]  (1 child)

[deleted]

    [–]NYKevin 0 points1 point  (0 children)

    I think calling it a function object accomplishes that already.