Closures Explained

L

Lasse Reichstein Nielsen

I've rewritten a short article explaining closures in JavaScript.
It's
at:

http://www.martinrinehart.com/articles/javascript-closures.html

A big Thank You to PointedEars and Jorge for helping me get closer to
the truth.

Comments:

In the example:
function outer() {
// args here
// code here
function inner() {
// more args and code
}
} // end of outer()
the "args here" comment seems slightly misleading. Arguments goes
between the parentheses. Maybe use:
function outer(/* arguments here *) {
instead.

The sentence "A closure is a bundle of data and code that manipulates
that data" is still indistinguishable from the description of an
Object.

A closure is a piece of code together with a binding of values to the
free variables of that code.

A free variable is one that occur in the code, but is not declared
there.

The next sentence, "In JavaScript it's a function with data that's
unavailable, except to the function." is closer, but also wrong.
The data, and even the bindings, might be available to other code too.

Example:

function pair(a,b) {
return {setFst : function(x){a=x;},
setSnd : function(x){b=x;},
sum : function() { return a+b; }};
}

var p = pair(2,4);
var s = p.sum; // s holds a clousre, but its data and bindings
// are available through, e.g., pair.setFst:
alert(s());
p.setFst(38);
alert(s());

So, what you describe as "What is a Closure?" isn't correct. It is
one use of a closure: to create functions with shared private variables.
It seems this use of closures is the focus of your page, but it should
really be named "private variables in Javascript, using closures" instead.

Closures are MUCH more than just that, e.g.:

function curry(f) {
return function(a) {
return function (b) {
return f(a,b);
}
}
}
function sum(a,b) { return a+b;};
var csum = curry(sum);
var inc = csum(1);
var addFive = csum(5);
alert([inc(41),addFive(37)]);


or it can be used to express something complicated in a simpler way:

function map(arr,f) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res = f(arr);
}
return res;
}

function cross(arr1,arr2) {
return map(arr1, function(x1) {
return map(arr2, function(x2) { return [x1,x2]; });
});
}

var pair_matrix = cross([1,2,3],[4,5,6]);
// pair_matrix ==
// [[[1,4],[1,5],[1,6]],
// [[2,4],[2,5],[2,6]],
// [[3,4],[3,5],[3,6]]]

(try doing it shorter using nested loops :)

And to prettify it:

alert(map(pair_matrix, function(a1) {
return map(a1, function(a2) {
return "(" + a2[0] + "," + a2[1] +")";
}).join(",");
}).join("\n"));

To put it bluntly: Closures allow you to write functional programs.
If only we had tail-calls, it would be perfect :)

/L
 
M

MartinRinehart

David said:
"I had the best books (Flanagan, Resig, Crockford)"

Flanagan has been proven clueless and Resig's books belong in the
comedy racks (or on a bonfire.)

And there isn't much there. This is a far superior article:

http://www.jibbering.com/faq/faq_notes/closures.html

Flanagan is listed in the FAQ as the best JavaScript book.

The jibbering article is good. However, it's 10 times longer. My goal
was to give some poor JavaScripter wannabe the basic idea so s/he
could get on with writing code.
 
M

MartinRinehart

the "args here" comment seems slightly misleading.
... between the parentheses. Maybe use:
Stupid me. That's 'vars'. Double dumb: the rewrite was on my computer,
not ULd. Fixed that, too.

I'll go through the rest of your points when I've got the time they
seem to deserve. Thanks.
 
J

Jorge

It gets off to a dubious start:

"I had the best books (Flanagan, Resig, Crockford)"

Flanagan has been proven clueless and Resig's books belong in the
comedy racks (or on a bonfire.)


A doubt a book by you or Mr. Speck would be better nor more
understandable nor more comprehensible. And sure you the Mr. I'm
perfect clan have your own dose of JS misunderstandings as well...
Nobody is perfect, no, not even Mr. Flanagan.

But because there are a couple of things or three that aren't 100%
perfect in 994 pages it doesn't mean that overall it's not an
excellent book.
Excellent means well above others, first-class. It's excellent.
 
D

David Mark

A doubt a book by you or Mr. Speck would be better nor more

Me or who?
understandable nor more comprehensible. And sure you the Mr. I'm

What do you know about some hypothetical book?
perfect clan have your own dose of JS misunderstandings as well...
Nobody is perfect, no, not even Mr. Flanagan.

Where are you going with this?
But because there are a couple of things or three that aren't 100%
perfect in 994 pages it doesn't mean that overall it's not an
excellent book.
Excellent means well above others, first-class. It's excellent.

Which "it" are you even talking about? AFAIK, they are all a waste of
money.
 
R

RobG

David said:
David Mark wrote: [...]
And there isn't much there.  This is a far superior article:
http://www.jibbering.com/faq/faq_notes/closures.html
Flanagan is listed in the FAQ as the best JavaScript book.
I thought it was listed as the lesser evil. It is not an endorsement.

http://jibbering.com/faq/#onlineResources

|  Although many books have been reviewed, most are quite bad and cannot
| be recommended.
|
| The following list of books been approved by CLJ regulars after
| critical review.

I would not include the phrase "after critical review", which infers
that a number of CLJ regulars have read it cover-to-cover and
commented on or approved all the facts presented. I don't recall
anyone here claiming to have done that, much less a sufficient number
of regulars for the statement to be true.

The book presents a number of topics outside the focus of this group
related to HTML, CSS, XML and others - there's even a section on E4X.
I don't recall anyone commenting on those sections, nor are those
topics regularly discussed here in any depth.

The general opinion (not held by everyone, but most I think) is that
it is the best of a bad lot. That sentiment should be maintained in
the text of the FAQ.
 
T

Thomas 'PointedEars' Lahn

I've rewritten a short article explaining closures in JavaScript.
It's at:

http://www.martinrinehart.com/articles/javascript-closures.html

| Unlike most JavaScript attributes (remember: all JavaScript variables are
| attributes)

"JavaScript", as understood in your article, has objects (e.g. Function
objects). Objects may have *properties* (e.g. `length'). Properties
(internally) may have attributes (e.g. `DontDelete').

Incidentally, your definition of "JavaScript" as "the subset of ECMAScript
that Crockford defines in his book, JavaScript: The Good Parts." is useless
to those who have not already bought and read the book.

And that were but the two paragraphs I am currently able to look into.
A big Thank You to PointedEars and Jorge for helping me get closer to
the truth.

You are welcome, although I think that you still have a long way to go and
will likely end up with what is in the FAQ, FAQ Notes, and newsgroup
archives. Especially, before trying to explain a complex concept such as
closures, you should get the basics right.


PointedEars
 
D

dhtml

Thomas said:
A "has" was missing if the statement was correct in the first place.

Indeed. Thank you. I did change the text. I found "Pocket Flanagan" was
summarily reviewed by JR Stockton and Jim Ley.
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
Double nonsense.

Reviews:
http://groups.google.com/group/comp..._frm/thread/b3c0f62bff45ea81/3eb57304bd05e85f
http://groups.google.com/group/comp.lang.javascript/msg/e533138dd37f45bf?dmode=source
http://groups.google.com/group/comp..._frm/thread/7283898f77fd2a66/c5f145ae807c918e


Douglas Crockford has provided approval on this list as well. (Though
the information is somewhat dated and of an older edition.)
http://groups.google.com/group/comp..._frm/thread/46a45facabbd1898/566d10b261b1a9c8

D. Flanagan himself has said that the Pocket Reference was "probably out
of date."
http://groups.google.com/group/comp.lang.javascript/msg/0866b23771e3a75e?dmode=source
 
T

Thomas 'PointedEars' Lahn

dhtml said:
Thomas said:
dhtml said:
David Mark wrote:
On Oct 10, 1:06 pm, (e-mail address removed) wrote:
Flanagan is listed in the FAQ as the best JavaScript book.
I thought it was listed as the lesser evil. It is not an endorsement.
http://jibbering.com/faq/#onlineResources
You meant said:
| Although many books have been reviewed, most are quite bad and cannot
| be recommended.
|
| The following list of books [has] been approved [...]
by CLJ regulars after critical review.
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^
Double nonsense.

Reviews:
http://groups.google.com/group/comp..._frm/thread/b3c0f62bff45ea81/3eb57304bd05e85f
http://groups.google.com/group/comp.lang.javascript/msg/e533138dd37f45bf?dmode=source
http://groups.google.com/group/comp..._frm/thread/7283898f77fd2a66/c5f145ae807c918e

As Lasse already said, those postings (especially comments on a few pages
and using that to make assumptions about the rest) do _not_ imply "critical
review".
Douglas Crockford has provided approval on this list as well. (Though
the information is somewhat dated and of an older edition.)
http://groups.google.com/group/comp..._frm/thread/46a45facabbd1898/566d10b261b1a9c8

Douglas Crockford may be knowledgable, but he is _not_ "regulars of CLJ",
and his posting certainly does _not_ imply "*critical* review". He does not
even state the reasons for his recommendation there. Nor does Jim Ley, and
given what Flanagan has posted in c.l.js, their judgement becomes rather
questionable. Ley's is apparently based on nothing but an "ipse dixit"
fallacy. And "not too bad" is certainly no endorsement.
D. Flanagan himself has said that the Pocket Reference was "probably out
of date."
http://groups.google.com/group/comp.lang.javascript/msg/0866b23771e3a75e?dmode=source

Irrelevant.


PointedEars
 
D

Dr J R Stockton

In comp.lang.javascript message <be9b7575-f8f6-4c31-950e-9ef78d55626a@k3
7g2000hsf.googlegroups.com>, Fri, 10 Oct 2008 10:06:52,
(e-mail address removed) posted:
Flanagan is listed in the FAQ as the best JavaScript book.

The jibbering article is good. However, it's 10 times longer. My goal
was to give some poor JavaScripter wannabe the basic idea so s/he
could get on with writing code.

On matters concerning those who need mainly to learn the simple basics,
there's little point in paying any attention to Lahn or Mark. They may
be right; but others will be more helpful.
 
D

David Mark

In comp.lang.javascript message <be9b7575-f8f6-4c31-950e-9ef78d55626a@k3
7g2000hsf.googlegroups.com>, Fri, 10 Oct 2008 10:06:52,
(e-mail address removed) posted:








On matters concerning those who need mainly to learn the simple basics,
there's little point in paying any attention to Lahn or Mark.  They may
be right; but others will be more helpful.

IIRC, Richard wrote the article in question. I think it is far more
helpful than this new one, even for beginners. Certainly it is the
first article on closures that I ever read and it really opened my
eyes to the possibilities (and pitfalls.)
 
D

Dr J R Stockton

In comp.lang.javascript message <[email protected]>
D. Flanagan himself has said that the Pocket Reference was "probably
out of date."
http://groups.google.com/group/comp.lang.javascript/msg/0866b23771e3a75
e?dmode=source

Any book user or buyer should check its publication date (the publisher
and the year should be added to the FAQ entries), and not expect it to
cover anything more recent.

Since most JavaScript is executed by an agent remote from the author, by
various browsers of various ages, an Internet author should be very wary
of using anything that is not in ISO/IEC 16262.

Pocket Flanagan 2, October 2002, should cover what is in ECMA 262.

For those Flanagans, the FAQ should link to index.html not toc.html;
index should link to toc.
 
J

John G Harris

Incidentally, your definition of "JavaScript" as "the subset of ECMAScript
that Crockford defines in his book, JavaScript: The Good Parts." is useless
to those who have not already bought and read the book.
<snip>

Moreover, the language Crockford defines isn't JavaScript, or even
javascript. It's a language where you aren't allowed to do

... { ... { ... } ... } ...

but if you want to pervert Crockford's prejudices you are allowed to do

... { ... if (true) { ... } ... } ...

instead.

This is one of the reasons why I think links to the Crockford book
should have a big warning label attached.

John
 
J

Jorge

I've rewritten a short article explaining closures in JavaScript.
It's
 at:

http://www.martinrinehart.com/articles/javascript-closures.html

A big Thank You to PointedEars and Jorge for helping me get closer to
the truth.

Declare an outer function, including any necessary parameters and
data. Declare an inner function. Have the outer function return the
inner function.

function outer([params]) {
// vars declared here
var closure = function([params]) { /* code here */ }

return closure;
}

Or, manage somehow to keep a reference to the inner function, one that
will last after the outer function has returned, as in:

var refSaver;

function outer([params]) {
// vars declared here
refSaver = function([params]) { /* code here */ }
}

Or:

function outer([params]) {
// vars declared here
window.onresize = function([params]) { /* code here */ }
}
 
J

Jorge

I've rewritten a short article explaining closures in JavaScript.
It's
 at:

http://www.martinrinehart.com/articles/javascript-closures.html

A big Thank You to PointedEars and Jorge for helping me get closer to
the truth.

"The execution context contains names and values of, among others,
variables, parameters and inner functions. When outer() returns a
function it also returns its execution context at the time of the
return."

The idea is something like:

0.- Upon entering a function, a new execution context is created for
it.
1.- The execution context of outer functions is accessible from within
any inner functions.
2.- When an outer function returns its current execution context is
destroyed unless reference(s) to inner function(s) survive.
3.- In that event, the execution context of the outer function can't
be destroyed until all the references to inner functions that have
access to it are destroyed as well.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,143
Latest member
SterlingLa
Top