L
Leo Meyer
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
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