I'm (re)learning Ajax from the Mozilla site on https://developer.mozilla.org/en/AJAX/Getting_Started, and I'm faced with this segment of code:
(function () {
var httpRequest;
document.getElementById("ajaxButton").onclick = function () {
makeRequest('test.html');
};
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
} //missing closing bracket added by bwalton 5/11/11. )();
While I managed to understand the code and get it working, it's not until I stripped off the "(function() {" part at the top and all the end braces at the end of this code segment. The thing is I don't understand the purpose of" (function{", and it seems neither does FF. (It doesn't recognize this segment as Javascript until I stripped off the "(function{" portions. Does anyone know the purpose of this segment of code? I knew I've seen it somewhere as well, and this time I want to know exactly what it means.
Thanks in advance for your help.