473,396 Members | 2,013 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,396 software developers and data experts.

Closures?

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) {
someobject.somevalue = x;
}
// set event handler
obj.onclick = eventhandler;
}

When the event handler is being called, the value of x at the time of the
call of f1 should be used. Unfortunately, this doesn't work; the value is
always 'undefined'. JavaScript probably tries to access the global variable
'x' which does not exist outside of f1's context.

I have tried a workaround:

function f1(x) {
var eventhandler = function(event) {
someobject.somevalue = this.x;
}
eventhandler.x = x;
// set event handler
obj.onclick = eventhandler;
}

This works in newer browsers (Firefox 1.5, IE 7). But not in IE 6; it seems
that anonymous functions can't have properties in IE 6's implementation :-(

Is there an elegant solution? I wouldn't want to use something like:

var fntext = "someobject.somevalue = " + x + ";";
var eventhandler = new Function("event", fntext);

because I find this hard to read and debug, especially if there are special
characters in the function body that need to be escaped.

Thanks for suggestions,

Leo


Oct 12 '06 #1
5 1713
Leo Meyer wrote:
Hello,

somewhere I have read that JavaScript supports closures. Does someone know
how to make them work?
Try this article that can be found from the FAQ, though not easily:

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >

Are you sure you need closures? Can you do the same thing with plain
old object properties?
>
What I want to do is this:

function f1(x, obj) {

var eventhandler = function(event) {
someobject.somevalue = x;
}
// set event handler
obj.onclick = eventhandler;
}

When the event handler is being called, the value of x at the time of the
call of f1 should be used. Unfortunately, this doesn't work; the value is
always 'undefined'. JavaScript probably tries to access the global variable
'x' which does not exist outside of f1's context.
[...]

Try this one:

<script type="text/javascript">

var objA = (function(){
var x;
return {
setX : function(val){ // Function to set value of x
x = val;
},
addClick : function(el){
el.onclick = function(){
alert('Value is: ' + x); // Closure to local x
}
}
}
})();

window.onload = function(){
objA.addClick(document.getElementById('button0'))
objA.addClick(document.getElementById('button1'))
}

</script>
<body>

<button id="button0">Button 0</button>
<button id="button1">Button 1</button>
<br><br><br>
<input id="inp0" value="10">
<button
onclick="objA.setX(document.getElementById('inp0') .value);">Set
value</button>

This works in newer browsers (Firefox 1.5, IE 7). But not in IE 6; it seems
that anonymous functions can't have properties in IE 6's implementation :-(
They certainly can, but you don't want (public) properties, you want
the equivalent of private members.

Is there an elegant solution? I wouldn't want to use something like:

var fntext = "someobject.somevalue = " + x + ";";
var eventhandler = new Function("event", fntext);
I don't think I understand what you want here...
--
Rob

Oct 12 '06 #2
Try this article that can be found from the FAQ, though not easily:
>
<URL: http://www.jibbering.com/faq/faq_notes/closures.html >
Thanks for the link. Excellent read.
>
Are you sure you need closures? Can you do the same thing with plain
old object properties?
aka "poops"? no thanks ;-)

Joke aside, the code from the original post works. I guess I made a mistake
somewhere else, as my "real" code is a bit more involved than the example I
posted.
>it seems
that anonymous functions can't have properties in IE 6's implementation
:-(

They certainly can, but you don't want (public) properties, you want
the equivalent of private members.
Accessibility isn't an issue in my situation. Concerning properties of
anonymous functions, the following code works in neither browser I have
tried:

<script type="text/javascript">
function f1(x, obj) {
var eventhandler = function(event) {
alert(this.x);
};
eventhandler.x = x;
// set event handler
obj.onclick = eventhandler;
}
window.onload=function(){
f1(5, document.getElementById("theA"));
f1(6, document.getElementById("theB"));
}
</script>
<a id="theA" href="#">theA produces 5</a><br>
<a id="theB" href="#">theB produces 6</a>
>var fntext = "someobject.somevalue = " + x + ";";
var eventhandler = new Function("event", fntext);

I don't think I understand what you want here...
I don't want it ;-) This is a very clumsy way to create a function.

Thanks & regards,
Leo
Oct 12 '06 #3
Leo Meyer wrote:

[snip]
Joke aside, the code from the original post works.
Good. I was going to ask for a link to a demonstration because it
certainly should have.

[snip]
var eventhandler = function(event) {
alert(this.x);
};
eventhandler.x = x;
// set event handler
obj.onclick = eventhandler;
You assign the value to a property of the function object, and then
expect to get it back using the this operator. The only way that could
happen is if the this operator referred to the function object, and
that's unlikely to occur unless the Function.prototype.apply or call
methods are used:

function myFunction() {
alert(this.property);
}
myFunction.property = 'value';

myFunction.call(myFunction);

or the function is called via another property that refers to the object:

function myFunction() {
alert(this.property);
}
myFunction.me = myFunction;
myFunction.property = 'value';

myFunction.me();

I think you'll agree that both are quite unlikely.

If the function was called directly, the this operator would refer to
the global object, so you would be looking for a property on the wrong
object. As it is, the function in your code is added as an event
listener. When the relevant event reaches that target (the element), the
function will be called as its method and the this operator will refer
to that element - you'd still be looking in the wrong place.

Mike
Oct 12 '06 #4
You assign the value to a property of the function object, and then expect
to get it back using the this operator. The only way that could happen is
if the this operator referred to the function object, and that's unlikely
to occur unless the Function.prototype.apply or call methods are used:
OK. I thought that "var eventhandler = function(event) {...}" created a new
function object, and that functions are called with the this operator set to
the function object. I see now that this is not necessarily the case.
If the function was called directly, the this operator would refer to the
global object, so you would be looking for a property on the wrong object.
As it is, the function in your code is added as an event listener. When
the relevant event reaches that target (the element), the function will be
called as its method and the this operator will refer to that element -
you'd still be looking in the wrong place.
Interesting. I've still got much to learn about JS.

Thanks and regards,
Leo
Oct 12 '06 #5
Leo Meyer wrote:

[snip]
I thought that "var eventhandler = function(event) {...}" created a
new function object,
If it's evaluated, it will.
and that functions are called with the this operator set to the
function object.
The value of the this operator is determined by /how/ the function is
called. You can find discussions of this topic in the Google Groups
archives[1] as it's a fairly frequently discussed issue.

Be aware that the poster using the pseudonym "VK" thinks he understands
this topic, and you'll find him rambling on about it often. Ignore
everything he writes: he hasn't the faintest clue.

[snip]
Thanks and regards,
You're welcome.
Mike
[1] (en) <http://groups.google.co.uk/group/comp.lang.javascript?hl=en>
(de) <http://groups.google.de/group/comp.lang.javascript?hl=de>
Oct 12 '06 #6

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

Similar topics

14
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...
5
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...
4
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...
2
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...
16
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,...
4
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-...
2
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...
26
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
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...
40
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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,...
0
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...

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.