Scoping the lobe

thoughts. consciousness. code. art.
Mon Aug 11
Wed Jul 9
Tue Jun 24
Wed May 7
Thu May 1
Mon Apr 21
Thu Mar 13
Tue Jan 22
Tue Jan 15
Mon Jan 7
Sat Dec 22
Tue Dec 18

Why closures are useful

Over here, there is some analysis of some crazy debate over adding closures to Java. It’s funny how the posts focus on closures being a means to circumvent the for loop. You could do that with good ole Functions as first class objects.

Closures are cool for so many other reasons. For example:

private function main():void
{
    var errorLabel:Label = new Label();
    var button:Button = new Button();
    
    button.addEventListener(MouseEvent.CLICK, function(evt:MouseEvent):void {
        errorLabel.text = "ERROR == don't click this button!";
    });
}

Holy shit, I just tossed a in-line function in that addEventListener method call and was able to reach out of the event handler scope and grab the reference to the errorLabel defined in the parent scope!

You could not do this without closures.  In fact, when your handler fired, you only get the event arg passed, so you’d need to do some lookup to get the errorLabel instance — walking the DOM or some such nonsense.   So this example shows how you can do something trivial but useful for fast development.

Here is something that has a bit more teeth to it:

var asyncRequest = function() {
function handleReadyState(o, callback) {
if (o && o.readyState == 4 && o.status == 200) {
if (callback) {
callback(o);
}
}
}
var getXHR = function() {
var http;
try {
http = new XMLHttpRequest;
getXHR = function() {
return new XMLHttpRequest;
};
}
catch(e) {
var msxml = [
‘MSXML2.XMLHTTP.3.0′,
‘MSXML2.XMLHTTP’,
‘Microsoft.XMLHTTP’
];
for (var i=0, len = msxml.length; i try {
http = new ActiveXObject(msxml[i]);
getXHR = function() {
return new ActiveXObject(msxml[i]);
};
break;
}
catch(e) {}
}
}
return http;
};
return function(method, uri, callback, postData) {
var http = getXHR();
http.open(method, uri, true);
handleReadyState(http, callback);
http.send(postData || null);
return http;
};
}();

This awesome optimization is made possible via closures.

Tue Dec 11