2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by Airshow
0

Formal definitions don't always help to penetrate "closure", though they do make sense once you understand.

If you learned about closures from PHP5, then you almost need to unlearn all that stuff first. PHP's implementation of closures is as bad and confusing as it gets (you actually need to use a keyword to force a closure!) while javascript's implementation is seriously elegant; it's so simple and natural that many programmers (me included) created closures by accident before we even knew it was a named concept. One day I looked at some code I was developing and said to myself, "that shouldn't work, surely that outer variable is out of scope! What is keeping it alive?" The answer (of course) was that a closure was formed where an outer function's scope (think of it as a little anonymous namespace) was kept alive, even after that outer function had completed and returned; it was kept alive simply by an inner function's use of one of the outer function's variables - no more than that.

THIS is a good place to start though you may need to read it though 2, 3, 4 times.

Other definitions and examples exist on the web but beware; some authors use "closure" as a synonym for "lambda", which is incorrect and very confusing. You will (quite correctly) find "lambda" used in discussions of "closure" but they are NOT the same thing.

Airshow

Edited by Airshow: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.