Silly things with JavaScript closures
From a theoretical programming point of view, JavaScript is immensely cool. You can do some amazing things with it. Although I’m not entirely sure whether you should.
For example I had a bunch of elements on a page I needed to update using AJAX. I needed a function I could pass the URLs and ids of elements to replace with those URLs and then have it perform each replacement in turn (I’ve seen IE have problems with simultaneous AJAX requests).
First I replace a simple replace_id
function that accepts three arguments. An element id, a URL to GET to replace its contents with and finally a function to be called when it’s all completed.
And then things got silly.
function chain_replace(urls, ids) {
id = 0;
next_id = function() {
if (id < = ids.length) {
return function() {
replace_id(urls[id], ids[id++], next_id());
}
}
};
next_id()();
}
Now the next_id()();
bit towards the end should be a clue that something a little odd is going on. But I must confirm that this code does actually work. With enough arguments it might make the browser explode with some sort of call stack problem though…