下面是https://github.com/Khan/khan-exercises/blob/master/khan-exercise.js自調用函數循環
for (var i = 0; i < loading; i++) (function(mod) {
if (!testMode && mod.src.indexOf("/khan-exercises/") === 0 && mod.src.indexOf("/MathJax/") === -1) {
// Don't bother loading khan-exercises content in production
// mode, this content is already packaged up and available
// (*unless* it's MathJax, which is silly still needs to be loaded)
loaded++;
return;
}
// Adapted from jQuery getScript (ajax/script.js)
var script = document.createElement("script");
script.async = "async";
for (var prop in mod) {
script[ prop ] = mod[ prop ];
}
script.onerror = function() {
// No error in IE, but this is mostly for debugging during development so it's probably okay
// http://stackoverflow.com/questions/2027849/how-to-trigger-script-onerror-in-internet-explorer
Khan.error("Error loading script " + script.src);
};
script.onload = script.onreadystatechange = function() {
if (!script.readyState || (/loaded|complete/).test(script.readyState)) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if (script.parentNode) {
script.parentNode.removeChild(script);
}
// Dereference the script
script = undefined;
runCallback();
}
};
head.appendChild(script);
})(urls[i]);
奇怪的代碼:而不是通常的for循環代碼塊中,我們看到自調用函數(內其他自調用函數),這是爲什麼!?這個函數將如何運行?
這是一個規則的循環。這實際上只是一個沒有{}的聲明。 – BNL
只有一個「自我調用函數」,它是爲'urls'數組中的每個元素執行的函數。唯一的其他功能是事件處理回調。 –
自調功能?廢話。你的意思是立即調用函數':P' –