我正在(重新)从https://developer.mozilla.org/en/AJAX/Getting_Started上的 Mozilla 站点学习 Ajax ,我面临着这段代码:
(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. )();
虽然我设法理解了代码并让它工作,但直到我剥离了顶部的“(function(){”部分和这段代码段末尾的所有结束括号。问题是我没有了解“(函数{”的目的,而FF似乎也没有。(在我剥离“(函数{”部分之前,它不会将此段识别为Javascript。有人知道这段代码的目的吗?)我知道我也在某个地方看到过它,这次我想知道它的确切含义。
在此先感谢您的帮助。