473,840 Members | 1,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

closures in JavaScript

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

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

I think I've understood. I look forward to your constructive critique.
Oct 3 '08 #1
4 1850
Ma************@ gmail.com wrote:
I've written a short article explaining closures in JavaScript. It's
at:

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

I think I've understood. I look forward to your constructive critique.
- A closure is _not_ "a bundle of data and code that manipulates that data";
that is how you could describe an *object* (and often it is done so),
which has properties and methods (which are merely callable properties in
ECMAScript implementations ) to operate on these properties.

A closure is instead a subroutine (function) that reproduces its
definition context when executed. This definition context would
contain what is called "bound variables" that can then be accessed
from within the subroutine when executed (cf. Wikipedia etc.)

- Inner functions, by which you mean function declarations within function
declarations, must be distinguished from function expressions that you
are using later in your article to create closures.

While both constructs can create a closure, the former cannot create
closures with bound "variables" that are created after variable
instantiation. In contrast to function expressions, function declarations
cannot be within a block statement, so they cannot be conditional (except
with evil[tm] eval()).

I find calling a function expression an "inner function" to be confusing
at best. That is a term that I would use only for nested function
declarations.

And while the Specification makes no statement regarding the nesting depth
of functions (be they declared or created through an expression), there is
most certainly a practical limit, stack size included. IIRC we have
discussed this here before.

- I disagree with your sentiment that JS/ES was more pythonic than Python;
knowing both languages quite well, when it comes to power of expression
ECMAScript implementations still have a lot to learn from Python.
Incidentally, they are beginning to: read Brendan Eich's blog regarding
this; then consider Array comprehensions being supported since JavaScript
1.7 (Gecko 1.8.1/Firefox 2.0.x), which is but a Python copycat.

- The statement "In addition to explicitly declared parameters and vars,
there are other things. You can access some of them directly, such as
this and arguments." is wrong, because neither of the mentioned features
are either parameters or variables.

`this' is a keyword and a (Reference) value that refers to the calling or
constructed object. `arguments' is a property (of the Activation/Variable
object).

- The statement "Other parts, such as the activation object and the
execution context are also present, but you cannot access them from
JavaScript." is wrong in its absoluteness, because you can access the
Activation Object of the global execution context with `this' because
the Global object is also the Variable Object of this context.

The execution context as such is not anything that is supposed to be
accessible in code because it is merely a theoretical construct.

- "When outer() returns a function it also returns a copy of its execution
context." No, it does not, that's nonsense; because again, the execution
context is only a theoretical construct.

Instead, when the Function object is created in outer() it would need to
retain some information about which of the "variables" (properties) in it
are bound to the execution context of outer() and which are not; probably
a copy of or a reference to the Variable Object of the execution context
created with the previous outer() call.

What is returned is a reference to the Function object. Whether or not
that Function object retains a copy of or a reference to the Variable
Object of the execution context created with the previous outer() call
instead, remains to be seen; I would presume this to be
implementation-dependent, although it would be more efficient to use
a reference.

- As for your example, where is `init()'?

- As for your summary, where is `grow'?
HTH

PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Oct 3 '08 #2
Thomas 'PointedEars' Lahn wrote:
- The statement "In addition to explicitly declared parameters and vars,
there are other things. You can access some of them directly, such as
this and arguments." is wrong, because neither of the mentioned features
are either parameters or variables.

`this' is a keyword and a (Reference) value that refers to the calling or
constructed object. `arguments' is a property (of the Activation/Variable
object).
Ignore that; I misunderstood your statement.

However, I think it is wrong to say that that (function) parameters are
declared: function *expressions* are _not_ *declarations* and still have a
parameter list (better: arguments). I am not sure what to use instead;
"Definition "/"defined" sounds better to me here.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Oct 3 '08 #3
On Oct 3, 4:29*pm, MartinRineh...@ gmail.com wrote:
I've written a short article explaining closures in JavaScript. It's
at:

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

I think I've understood. I look forward to your constructive critique.
Martin,

I don't agree with this:

"Some things are worth repeating: When outer() returns a function it
also returns a copy of its execution context. That is not a reference
to its execution context, it is a copy. (Probably it's a reference to
a copy, but that's an implementation detail we don't need to worry
about.) That is why I added "Sort of." when I said the closure had
access to the vars (and so on) of the outer function. It really has
access to a new set of vars (and so on) that are an exact copy of the
outer function's execution context at the time the closure was
returned by outer()."

I think that the execution context of the outer function is not copied
nowhere, it's just that it's not destroyed, it's kept in memory for as
long as the references to inner functions exist. It will last as long
as those references. Consider this example:

<html><head>
<script>
window.onload= function () {
var e, capturedInAClos ure= 0;
document.body.a ppendChild(e=
document.create Element('button ')).innerHTML= "doIt";
e.onclick= function () { e.innerHTML= ++capturedInACl osure };
document.body.a ppendChild(e=
document.create Element('button ')).innerHTML= "doItAgain" ;
e.onclick= function () { e.innerHTML= ++capturedInACl osure };
document.body.a ppendChild(e= document.create Element('p')).i nnerHTML=
capturedInAClos ure;
};
</script>
</head><body></body></html>

2 references to 2 inner functions remain after returning from
window.onload: doIt.onclick() and doItAgain.oncli ck(). Both point to
the very same 'capturedInAClo sure' var, end the very same 'e'. So they
are sharing the execution context of window.onload. It's not 'a copy'
nor a 'new set of vars that are an exact copy' of the outer function.

Don't you think so ?

--
Jorge.
Oct 3 '08 #4
On Oct 3, 8:37*pm, Jorge <jo...@jorgecha morro.comwrote:
>
2 references to 2 inner functions remain after returning from
window.onload: doIt.onclick() and doItAgain.oncli ck(). Both point to
the very same 'capturedInAClo sure' var, end the very same 'e'. So they
are sharing the execution context of window.onload. It's not 'a copy'
nor a 'new set of vars that are an exact copy' of the outer function.
Also, everytime the outer function is called, a new execution context
is created:

<html><head>
<script>
window.onload= function () {
var e, capturedInAClos ure= 0;
document.body.a ppendChild(e=
document.create Element('button ')).innerHTML= "doIt";
e.onclick= function () { e.innerHTML= ++capturedInACl osure };
document.body.a ppendChild(e=
document.create Element('button ')).innerHTML= "doItAgain" ;
e.onclick= function () { e.innerHTML= ++capturedInACl osure };
document.body.a ppendChild(e= document.create Element('p')).i nnerHTML=
capturedInAClos ure;
if (!arguments.cal lee.inited) {
arguments.calle e.inited= true;
setTimeout(wind ow.onload,0);
setTimeout(wind ow.onload,0);
setTimeout(wind ow.onload,0);
}
};
</script>
</head><body></body></html>

--
Jorge.
Oct 3 '08 #5

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

Similar topics

14
1584
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
1726
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
2423
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
3065
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
10
2086
by: Emre Sevinc | last post by:
Take a look at the following snippet: <html> <head> <script> function add(elementId) { var container = document.getElementById(elementId); for (var i = 0; i < 10; i++) { var elt = document.createElement('div'); elt.innerHTML = "" + i;
5
1731
by: Leo Meyer | last post by:
Hello, somewhere I have read that JavaScript supports closures. Does someone know how to make them work? What I want to do is this: function f1(x, obj) { var eventhandler = function(event) {
16
1300
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):
40
1880
by: MartinRinehart | last post by:
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.
0
9856
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
9698
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
10914
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
10597
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...
1
7834
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
7022
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
5684
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
5872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3136
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.