473,378 Members | 1,393 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

How to "freeze" a constant into a closure?

Here's some JavaScript that does not do what I would like it to do:

var x = new Object();
var y = new Object();
var j;
for (j=0; j<5; j++) {
x['f'+j] = function () { print(j); };
}
for (j=0; j<5; j++) {
var jj = 0+j;
y['f'+j] = function () { print(jj); };
}

x.f0(); // prints 5
y.f0(); // prints 4

I want object x to contain 5 functions, each of which prints a
different value. (Actually, I'm building an HTML form with a table
where any row can be removed by clicking a button in that row...) The
two approaches above do not work. I've tried some tricks with eval,
but they don't work either. Any idea on how to do this?

--
DLL
Apr 2 '08 #1
5 1777
On Apr 2, 5:37*pm, David Lee Lambert <dav...@lmert.comwrote:
I want object x to contain 5 functions, *each of which prints a
different value. *...
--
DLL
I figured out how to do it:
function makePrintClosure (val) {
return function () { print(val); }
}
var x = new Object();
var j;
for (j=0; j<5; j++) {
x['f'+j] = makePrintClosure(j);
}

x.f0();
Apr 2 '08 #2
David Lee Lambert <da****@lmert.comwrites:
Here's some JavaScript that does not do what I would like it to do:

var x = new Object();
var y = new Object();
var j;
for (j=0; j<5; j++) {
x['f'+j] = function () { print(j); };
}
for (j=0; j<5; j++) {
var jj = 0+j;
y['f'+j] = function () { print(jj); };
}

x.f0(); // prints 5
y.f0(); // prints 4
You're closing over global variables. You want to close over newly
instantiated variables instead. Something like this:

for (var j=0; j<5; j++) {
x['f'+j] = (function(i) { return function () { print(i); } })(j);
}

or if you prefer:

for (var j=0; j<5; j++) {
x['f'+j] = (function() {
var i = j;
return function () { print(i);
} })();
}

Note that javascript does NOT have a block scope, which is why your
second attempt also closes over a global. Variables are function-scoped
only.

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Apr 2 '08 #3
On Apr 3, 8:03 am, David Lee Lambert <dav...@lmert.comwrote:
On Apr 2, 5:37 pm, David Lee Lambert <dav...@lmert.comwrote:
I want object x to contain 5 functions, each of which prints a
different value. ...
--
DLL

I figured out how to do it:

function makePrintClosure (val) {
return function () { print(val); }

}

var x = new Object();
var j;
for (j=0; j<5; j++) {
x['f'+j] = makePrintClosure(j);

}

x.f0();
You might find the following link about implementing private
variables and privileged functions useful:

<URL: http://www.litotes.demon.co.uk/js_in...te_static.html >
--
Rob
Apr 6 '08 #4
Joost Diepenmaat wrote:
[...]
IMHO this is one of the annoying things about javascript's function
scope. If it had some additional way to creating scope that would
probably be optimized a lot better, and written a bit clearer. For
instance:

for (var j=0; j<5; j++) {
let (i = j) {
x['f'+i] = function(i) { print (i) };
}
}
JavaScript[tm] does have that since version 1.7:

http://PointedEars.de/es-matrix/#l
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8*******************@news.demon.co.uk>
Jun 27 '08 #5
Thomas 'PointedEars' Lahn <Po*********@web.dewrites:
Joost Diepenmaat wrote:
>[...]
IMHO this is one of the annoying things about javascript's function
scope. If it had some additional way to creating scope that would
probably be optimized a lot better, and written a bit clearer. For
instance:

for (var j=0; j<5; j++) {
let (i = j) {
x['f'+i] = function(i) { print (i) };
}
}

JavaScript[tm] does have that since version 1.7:

http://PointedEars.de/es-matrix/#l
Hah, nice!

I really should read up on those newer JavaScript versions, but
unfortunately 99% of my current JS work is supposed to run on all the
"popular" browsers, not just Mozilla.

Cheers,
Joost.

--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Jun 27 '08 #6

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

Similar topics

11
by: Joseph Turian | last post by:
Fellow hackers, I have a class BuildNode that inherits from class Node. Similarly, I have a class BuildTree that inherits from class Tree. Tree includes a member variable: vector<Node>...
11
by: Matt Kruse | last post by:
This is a common requirement - "freeze panes" in a table, so that some header rows and some columns on the left are frozen while the body content scrolls. This makes large tables more usable on...
4
by: Colleyville Alan | last post by:
I have an app in which users can select stuff from a multi-column listbox. There are something like 30 columns of info for each item and all are included in the listbox. When I scroll to the right...
1
by: (Pete Cresswell) | last post by:
I've got about 4,000 mutual funds. Each fund currently has up to 255 "returns" associated with it. A 'return' being a decimal number and a date for that fund. I have a feeling that the...
0
by: Michael Williams | last post by:
Can anyone explain why "freeze.py" will make binaries with the std modules fine, however, when using 3rd party modules (Pexpect in particular) it requires the target system to actually have it...
10
by: morangolds | last post by:
Hi, I've been having a problem with C++ Windows Forms apps not "ending" when you close the form window. I've searched about this problem all over the place and most searches have lead me to...
1
by: guy.flowers | last post by:
Hi Have a problem, Ill give some history to the problem and add a little example code to start with to see if anybody can help or if I am correct in what the problem is. I have been looking...
1
by: kdpo1990 | last post by:
I've worked with ASP.NET apps. for a long time, but now, i have to figure out how to do same in win app. I need to find a way to lock or freeze table column in datagrid. This is a link to an...
2
by: oopaevah | last post by:
I am using the Microsoft.XMLHTTP object to make server requests ie; ajax. This is working 99% of the time but occasionally it will freeze at the server for 5 minutes and then raise a javascript...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.