473,757 Members | 2,320 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
40 1865
Jorge <jo***@jorgecha morro.comwrites :
On Oct 10, 5:38*pm, MartinRineh...@ gmail.com wrote:
"Some authors said (and this was where I got confused) that the
closure has access to the variables of the outer function. This is
sort of true. Really it has access to the variable's names and values
at the moment the closure is created."

This isn't clear enough... a bit messy.
It's also wrong. The closure has access to the actual variables, not
just their value at the time the closure was created, including any
change to the variable, before or after the closure was created.T

That's why the following doesn't work as most people expect it to:

for (var i = 0; i < 10; i++) {
setTimeout(func tion(){alert(i) ;},i*2000);
}

It alerts "10" all ten times.

/L
--
Lasse Reichstein Holst Nielsen
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Oct 11 '08 #21
On Oct 10, 5:38*pm, MartinRineh...@ gmail.com wrote:
I've rewritten a short article explaining closures in JavaScript.
It's
*at:

http://www.martinrinehart.com/articl...-closures.html
"Really it has access to the variable's names and values
at the moment the closure is created."

No 'memory effects': in this example there are 10 different inner
functions that survive after the outer (window.onload) function
returns. They are created at different times and at different values
of 'n'. But they all alert the same value: the value that n has in the
(left orphan by window.onload's return) execution context of the outer
function: 10.

See: http://jorgechamorro.com/cljs/020/

<script>
window.onload= function () {
var e, n;
for (n=0; n<10; n++) {
document.body.a ppendChild(
e= document.create Element('button '
)).innerHTML= n;
e.onclick= function () { alert(n) };
}
};
</script>

--
Jorge.
Oct 11 '08 #22
On Oct 12, 12:13*am, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
wrote:
(...)
That's why the following doesn't work as most people expect it to:

*for (var i = 0; i < 10; i++) {
* *setTimeout(fun ction(){alert(i );},i*2000);
*}

It alerts "10" all ten times.

On Oct 12, 12:17 am, Jorge <jo...@jorgecha morro.comwrote:
>
(..) But they all alert the same value: the value that n has in the
(left orphan by window.onload's return) execution context of the outer
function: 10.
LOL :-)

--
Jorge.
Oct 11 '08 #23
In comp.lang.javas cript message <gc**********@r egistered.motza rella.org>
, Fri, 10 Oct 2008 18:23:40, dhtml <dh**********@g mail.composted:
>D. Flanagan himself has said that the Pocket Reference was "probably
out of date."
http://groups.google.com/group/comp....866b23771e3a75
e?dmode=sour ce
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.

--
(c) John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v6.05 MIME.
Web <URL:http://www.merlyn.demo n.co.uk/- FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "" (SonOfRFC1036)
Oct 11 '08 #24
On Oct 10, 8:44*am, David Mark <dmark.cins...@ gmail.comwrote:
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
I think "clueless" is incorrect and inappropriate. He knows a lot as
displayed many times in his book and I still find his book a useful
starting resource for most browser-related issues. Yes his book has
mistakes but that does not make him clueless.

Peter
Oct 12 '08 #25
On Oct 10, 10:06*am, 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.
"best" is a comparative term.

The jibbering article is a good resource.

Peter
Oct 12 '08 #26
On 2008-10-12 19:49, John G Harris wrote:
>>Moreover, the language Crockford defines isn't JavaScript, or even
javascript. It's a language where you aren't allowed to do

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

Where does he say that?

In the syntax diagrams.
OK, I see what you mean. This is on the same page where he writes that
"if(expression) " can only be followed by a block. The grammar he's
defining here is not that of javascript, but of the subset he calls the
Good Parts. That's the whole point of the book - dividing the language
into good and bad (and, in the appendix, awful) parts. I think most
people who work with any language for a while instinctively do the same
thing in their minds, and Crockford wrote a book about it. As I said,
it's not a tutorial, but a collection of opinions.
I don't think he says in words that he doesn't want to nest blocks.
Perhaps he couldn't think of any way of discouraging people from doing

... { ... if (true) { ... } ... } ...
Off the top of my head I can't think of a single reason to use a block
unless it's necessary (except following if/else/for/while/etc, which is
a question of coding style) so I think that excluding them from the Good
Parts was the correct choice. "if (true) {...}" doesn't make any sense
at all.
For the record, I do disagree on quite a number of other suggestions and
opinions in the book, but that hardly made it worthless for me.
- Conrad
Oct 12 '08 #27
On Oct 12, 2:41*pm, Peter Michaux <petermich...@g mail.comwrote:
On Oct 10, 8:44*am, David Mark <dmark.cins...@ gmail.comwrote:
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

I think "clueless" is incorrect and inappropriate. He knows a lot as
His name has come up here a lot over the years. It seems to me that
most of it was bad. I certainly wouldn't recommend buying his books.
He's no Resig when it comes to cluelessness. I'll leave it at that.
Oct 13 '08 #28
On Oct 12, 7:15*pm, David Mark <dmark.cins...@ gmail.comwrote:
On Oct 12, 2:41*pm, Peter Michaux <petermich...@g mail.comwrote:
On Oct 10, 8:44*am, David Mark <dmark.cins...@ gmail.comwrote:
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
I think "clueless" is incorrect and inappropriate. He knows a lot as

His name has come up here a lot over the years. *It seems to me that
most of it was bad.
People seem to like to point out the mistakes because that is actually
useful. It would be boring and pointless to read about all the he
wrote that are correct.

I certainly wouldn't recommend buying his books.
That is a different story. I would recommend his book but would warn
that there are errors both small and large. I think a beginner is best
served by a paper book that covers the language and the DOM.
Flanagan's book fits that bill best of the options available. It isn't
so good to say to a beginner, "hey there are some documents on there
and there on the web. Try the terse specs and the Mozilla site and the
archives of c.l.js are good but there is a lot of pedantic arguing to
wade through. Just jump in the deep end with the sharks." Flangan's
book is a much more gentle introduction.

Peter
Oct 13 '08 #29
On Oct 10, 9:07*pm, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
wrote:
>
[snip]

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.
So does it mean that even global variables in Javascript are `free
variables' given the fact that they can be used without being declared
or is it that the definition is a loose one?

Also, given the function:

---------------------------------->B--------------------------
function attachEvents() {
var divs = document.getEle mentsByTagName( "DIV");
if(!divs) return;
for(var i = 0, maxI = divs.length; i < maxI; ++i) {
var d = divs[i];
d.onclick = function() {
// some complicated processing with a lot of variables
alert("Hello from " + d.id);
}
}
}
window.onload = function() {
attachEvents();
// something complicated
attachEvents();
}
---------------------------------->B--------------------------

Will the second invocation of the function `attachEvents' make the
execution context of the first run along with the previously created
function objects eligible for garbage collection or do they need to be
explicitly grounded [set to null]?

/sasuke
Oct 13 '08 #30

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

Similar topics

14
1577
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
1722
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
2419
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
3059
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
1289
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
1453
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
1847
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
9487
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10069
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
9904
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
9735
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8736
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...
0
5324
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3395
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2697
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.