473,769 Members | 6,473 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 1867
sasuke <da*********@gm ail.comwrites:
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?
I variable is not inherently free or not. A variable occurence in a
part of a program, e.g., function declaration, is free in that
function if the function doesn't contain a declaration of that variable.

Example:

function foo(x) {
return function(y) {
alert(x+y);
}
}

This entire function has only one free variable: "alert".
The variable occurences "x" and "y" are bound by the argument
declarations of the surrounding functions.

The inner function:
function(y) { alert(x+y); }
has two free variables: "alert" and "x".

Notice that the same occurence of "x" can be both free and bound
depending on the scope one consider.

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]?
That depends entirely on the javascript implementation.

Best case, nothing remains and the garbage collector claims it all.

Worst case, the garbage collector barfs on the DOM->JS function->DOM
dependencies and collects nothing. That's a memory leak. I believe
IE 6 might do just that.

/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 13 '08 #31
On Oct 13, 1:14*pm, sasuke <database...@gm ail.comwrote:
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?
The term "free variable" (as defined here) could be used to describe
global variables that are referenced within functions. Regardless,
global variables are not part of the binding described in the closure
definition.
>
Also, given the function:

---------------------------------->B--------------------------
function attachEvents() {
* var divs = document.getEle mentsByTagName( "DIV");
Inefficient. Use the collection itself.
* if(!divs) return;
You don't need to do that with gEBTN.
* for(var i = 0, maxI = divs.length; i < maxI; ++i) {
Inefficient. Use a while that counts down to 0.
* * var d = divs[i];
* * d.onclick = function() {
* * * // some complicated processing with a lot of variables
* * * alert("Hello from " + d.id);
* * }
* }}
You are leaking memory. Every one of these creates this chain:

[DOM element X] ---onclick---[anon function] ---[variable object]
---[DOM element A]

You forgot to set divs to null too. Same issue.

Unfortunately, your design doesn't allow you to set d to null.

function attachEvents() {
var el, index = document.getEle mentsByTagName( 'div').length;
while (index--) {
el = document.getEle mentsByTagName( 'div')[index];
el.onclick = (function(id) {
return function() { alert('Hello from ' + id); };
})(el.id);
}
el = null;
}

Or better yet, attach one listener and use delegation.
Oct 13 '08 #32
On Oct 13, 2:56*pm, David Mark <dmark.cins...@ gmail.comwrote:
On Oct 13, 1:14*pm, sasuke <database...@gm ail.comwrote:
[snip]
---[DOM element A]
Typo. Should be X of course (not A.) The whole point is that it is a
circular reference.
Oct 13 '08 #33
On Oct 13, 8:56*pm, David Mark <dmark.cins...@ gmail.comwrote:
>
function attachEvents() {
* var el, index = document.getEle mentsByTagName( 'div').length;
* while (index--) {
* * *el = document.getEle mentsByTagName( 'div')[index];
* * *el.onclick = (function(id) {
* * * * return function() { alert('Hello from ' + id); };
* * *})(el.id);
* }
* el = null;

}

function attachEvents () {
var divs= document.getEle mentsByTagName( 'div'),
f= function (event) { alert(this.id) },
index= divs.length;

while (index--) { divs[index].onclick= f }
}

--
Jorge.
Oct 14 '08 #34
On Oct 14, 10:00*am, Jorge <jo...@jorgecha morro.comwrote:
On Oct 13, 8:56*pm, David Mark <dmark.cins...@ gmail.comwrote:
function attachEvents() {
* var el, index = document.getEle mentsByTagName( 'div').length;
* while (index--) {
* * *el = document.getEle mentsByTagName( 'div')[index];
* * *el.onclick = (function(id) {
* * * * return function() { alert('Hello from ' + id); };
* * *})(el.id);
* }
* el = null;
}

function attachEvents () {
* var divs= document.getEle mentsByTagName( 'div'),
* f= function (event) { alert(this.id) },
* index= divs.length;

* while (index--) { divs[index].onclick= f }

}
It is pointless to rewrite this pattern (diminishing returns.) A
single listener should be used.
Oct 14 '08 #35
On Oct 14, 10:00*am, Jorge <jo...@jorgecha morro.comwrote:
On Oct 13, 8:56*pm, David Mark <dmark.cins...@ gmail.comwrote:
function attachEvents() {
* var el, index = document.getEle mentsByTagName( 'div').length;
* while (index--) {
* * *el = document.getEle mentsByTagName( 'div')[index];
* * *el.onclick = (function(id) {
* * * * return function() { alert('Hello from ' + id); };
* * *})(el.id);
* }
* el = null;
}

function attachEvents () {
* var divs= document.getEle mentsByTagName( 'div'),
* f= function (event) { alert(this.id) },
* index= divs.length;

* while (index--) { divs[index].onclick= f }

}
Oops, forgot to mention that this will leak memory in IE.

[divs]->[DOM node]->[f]->[variable object]->[divs]

Add divs = null to break the chain at the end (of course.)

See the link posted previously.
Oct 14 '08 #36
David Mark <dm***********@ gmail.comwrites :
On Oct 14, 7:16*am, Conrad Lender <crlen...@yahoo .comwrote:
>[second attempt; the first didn't show up for some reason]

On 2008-10-13 20:56, David Mark wrote:
function attachEvents() {
* var el, index = document.getEle mentsByTagName( 'div').length;
* while (index--) {
* * *el = document.getEle mentsByTagName( 'div')[index];

Are you suggesting that calling getElementsByTa gName() in a loop is more
efficient than storing a reference to the collection in a variable, and

Yes. Browsers optimize for that pattern.
Do you have any references for that? It sounds likely that they do
something smart, but I find it unlikely that it will be faster
to call a function to return the same value again than just looking
it up in a local variable.
Nonsense. Opera has a long article on their site about this.
Link?

/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 14 '08 #37
On Oct 14, 6:32*pm, Lasse Reichstein Nielsen <lrn.unr...@gma il.com>
wrote:
David Mark <dmark.cins...@ gmail.comwrites :
On Oct 14, 7:16*am, Conrad Lender <crlen...@yahoo .comwrote:
[second attempt; the first didn't show up for some reason]
On 2008-10-13 20:56, David Mark wrote:
function attachEvents() {
* var el, index = document.getEle mentsByTagName( 'div').length;
* while (index--) {
* * *el = document.getEle mentsByTagName( 'div')[index];
Are you suggesting that calling getElementsByTa gName() in a loop is more
efficient than storing a reference to the collection in a variable, and
Yes. *Browsers optimize for that pattern.

Do you have any references for that? It sounds likely that they do
I have been trying to dig it up myself.
something smart, but I find it unlikely that it will be faster
Thanks for that, but it is possible that I did something dumb in this
case. The fact that I can't find the article is not encouraging.
to call a function to return the same value again than just looking
it up in a local variable.
Well, define looking it up in a local variable when the local variable
is a reference to a live nodelist? I can't as I don't write browsers.
>
Nonsense. *Opera has a long article on their site about this.

Link?
Not on Opera from what I can see.
Oct 14 '08 #38
On 2008-10-14 23:42, David Mark wrote:
function attachEvents() {
var el, index = document.getEle mentsByTagName( 'div').length;
while (index--) {
el = document.getEle mentsByTagName( 'div')[index];

Are you suggesting that calling getElementsByTa gName() in a loop is more
efficient than storing a reference to the collection in a variable, and

Yes. Browsers optimize for that pattern.
I would also like to see a source for that.
>using the variable in the loop? I doubt that, and some preliminary

Doubt it all you want.
>testing shows that your recommendation is consistently slower than
sasuke's; in some implementations (Opera, Safari) even by a factor of 4.

Nonsense. Opera has a long article on their site about this.
Well. Here I am, having tested this in 5 current browsers (not
comprehensive, yes, but as I said, they were preliminary tests), and
here you are saying "nonsense". Is that all you've got?
- Conrad
Oct 14 '08 #39
On Oct 14, 6:54*pm, Conrad Lender <crlen...@yahoo .comwrote:
On 2008-10-14 23:42, David Mark wrote:
function attachEvents() {
* var el, index = document.getEle mentsByTagName( 'div').length;
* while (index--) {
* * *el = document.getEle mentsByTagName( 'div')[index];
Are you suggesting that calling getElementsByTa gName() in a loop is more
efficient than storing a reference to the collection in a variable, and
Yes. *Browsers optimize for that pattern.

I would also like to see a source for that.
using the variable in the loop? I doubt that, and some preliminary
Doubt it all you want.
testing shows that your recommendation is consistently slower than
sasuke's; in some implementations (Opera, Safari) even by a factor of 4.
Nonsense. *Opera has a long article on their site about this.

Well. Here I am, having tested this in 5 current browsers (not
Yes, there you are. Your testing has been previously proven suspect.
Pardon me if I am non-responsive.
Oct 14 '08 #40

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

Similar topics

14
1578
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
1290
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
2811
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
9423
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
10216
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
9865
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
8873
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
7413
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
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5309
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
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2815
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.