473,729 Members | 2,344 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Closures Explained

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

http://www.martinrinehart.com/articl...-closures.html

A big Thank You to PointedEars and Jorge for helping me get closer to
the truth.
Oct 10 '08 #1
40 1859
On Oct 10, 11:38*am, MartinRineh...@ gmail.com wrote:
I've rewritten a short article explaining closures in JavaScript.
It's
*at:

http://www.martinrinehart.com/articl...-closures.html
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.)

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

http://www.jibbering.com/faq/faq_notes/closures.html
Oct 10 '08 #2
Ma************@ gmail.com writes:
I've rewritten a short article explaining closures in JavaScript.
It's
at:

http://www.martinrinehart.com/articl...-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 indistinguishab le 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[i] = f(arr[i]);
}
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
--
Lasse Reichstein Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Oct 10 '08 #3


David Mark wrote:
"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.
Oct 10 '08 #4
On Oct 10, 12:07*pm, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
wrote:
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.
Oct 10 '08 #5
On Oct 10, 1:06*pm, MartinRineh...@ gmail.com wrote:
David Mark wrote:
"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.
I thought it was listed as the lesser evil. It is not an endorsement.
Oct 10 '08 #6
David Mark wrote:
On Oct 10, 1:06 pm, MartinRineh...@ gmail.com wrote:
>David Mark wrote:
>>"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.

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

Garrett
Oct 10 '08 #7
On Oct 10, 5:44*pm, David Mark <dmark.cins...@ gmail.comwrote:
>
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 misunderstandin gs 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.

--
Jorge.
Oct 10 '08 #8
On Oct 10, 5:33*pm, Jorge <jo...@jorgecha morro.comwrote:
On Oct 10, 5:44*pm, David Mark <dmark.cins...@ gmail.comwrote:
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
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 misunderstandin gs 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.
Oct 10 '08 #9
dhtml wrote:
David Mark wrote:
>On Oct 10, 1:06 pm, MartinRineh...@ gmail.com wrote:
>>David Mark wrote:
"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.

I thought it was listed as the lesser evil. It is not an endorsement.

http://jibbering.com/faq/#onlineResources
You meant <http://jibbering.com/faq/#books>.
| Although many books have been reviewed, most are quite bad and cannot
| be recommended.
|
| The following list of books been approved
A "has" was missing if the statement was correct in the first place.
by CLJ regulars after critical review.
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^
Double nonsense.
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <http://www.vortex-webdesign.com/help/hidesource.htm>
Oct 11 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
1573
by: Alexander May | last post by:
When I define a function in the body of a loop, why doesn't the function "close" on the loop vairable? See example below. Thanks, Alex C:\Documents and Settings\Alexander May>python Python 2.3.3 (#51, Dec 18 2003, 20:22:39) on win32 Type "help", "copyright", "credits" or "license" for more information.
5
1721
by: paolo veronelli | last post by:
I've a vague idea of the differences,I don't know scheme anyway. I'd like to see an example to show what is missing in python about closures and possibly understand if ruby is better in this sense. Iuse ruby and python in parallel for my job just to learn them and their differences and python is shorter and cleaner ,but i feel it's missing something, in closures.Any hints?
4
2418
by: Marc Tanner | last post by:
Hello, I am currently working on a eventhandling system or something similar, and have the problem of loosing scope. I have read many interesting posts on this group and the faq article about closure, but it seems that i have still not understood everything. Below is my attempt to preserve the scope but it's not really nice and i think with the use of closure could it be done better. But at the moment i am quite confused and hope that...
2
3055
by: Jake Barnes | last post by:
Using javascript closures to create singletons to ensure the survival of a reference to an HTML block when removeChild() may remove the last reference to the block and thus destory the block is what I'm hoping to achieve. I've never before had to use Javascript closures, but now I do, so I'm making an effort to understand them. I've been giving this essay a re-read: http://jibbering.com/faq/faq_notes/closures.html
16
1287
by: Karl Kofnarson | last post by:
Hi, while writing my last program I came upon the problem of accessing a common local variable by a bunch of functions. I wanted to have a function which would, depending on some argument, return other functions all having access to the same variable. An OO approach would do but why not try out closures... So here is a simplified example of the idea: def fun_basket(f):
4
1450
by: king kikapu | last post by:
Hi, i am trying, to no avail yet, to take a C#'s overloaded functions skeleton and rewrite it in Python by using closures. I read somewhere on the net (http://dirtsimple.org/2004/12/python-is- not-java.html) that in Python we can reduce code duplication for overloaded functions by using closures. I do not quite understand this. Let's say we have the following simple C# code:
2
1566
by: Jon Harrop | last post by:
Just debating somewhere else whether or not Python might be considered a functional programming language. Lua, Ruby and Perl all seem to provide first class lexical closures. What is the current state of affairs in Python? Last time I looked they were just removing (?!) closures... -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com/products/?u
26
2810
by: Aaron \Castironpi\ Brady | last post by:
Hello all, To me, this is a somewhat unintuitive behavior. I want to discuss the parts of it I don't understand. .... f= lambda: n .... 9 9
4
1845
by: MartinRinehart | last post by:
I've written a short article explaining closures in JavaScript. It's at: http://www.martinrinehart.com/articles/javascript-closures.html I think I've understood. I look forward to your constructive critique.
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9281
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8148
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4525
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2680
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2163
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.