On 15/03/2006 21:05, windandwaves wrote:
web.dev wrote:
windandwaves wrote:
[snip]
function load_images() {
if (!check()) return;
var nav = document.getElementById('frm');
var imgs = nav.getElementsByTagName('img');
var x = 0;
for (var i =0;i<imgs.length;i++) {
imgs[i].number = i;
imgs[i].onclick = select_image;
var y = 'c' + x;
clicker[i] = new getObj(y);
clicker[i].obj.onclick = function () {tick_image(x);};
x++;
}
[snip]
then I always get 12 rather than a number between 0 and 11.
[snip]
You need to separate the assignment of functions when you want to
pass a variable to a function.
[snip]
I have no idea why but it works! Would you care explaining it?
This is a rather fundamental feature of inner functions, and therefore
closures.
An inner function maintains a reference to the Variable object of each
outer function in a stack, ending with the global object. This is the
scope chain. The Variable objects it references contain local variables
as properties. It is the scope chain that is used to resolve identifiers.
Each time your loop executes, a new function object is created, and a
reference is assigned to the onclick property. While each object is new,
the scope chain is exactly the same. This means that each function
object shares the same set of variables as each one reference the same
Variable objects.
The conclusion? If one function changes the value of a variable, all of
these inner functions sees that change. Now, whilst your function
doesn't perform any modifications, the loop code does and the effect is
the same: by the end of the loop, each function will read the variable,
i, to be the value of img.length.
[snip]
By the way, you should consider removing those event listeners (assign
null to the onclick properties) when the document unloads to avoid
invoking IE's notorious memory leak.
You should also remove
clicker[i].obj.onclick = function () {tick_image(x);};
from the load_images function. It's redundant now.
Mike
--
Michael Winter
Prefix subject with [News] before replying by e-mail.