[英]javascript anonymous function call with parameter
有人可以在匿名函數調用中解釋參數e
。 我無法理解匿名函數如何接受參數(以下代碼的第二行)。 此代碼取自DropZone
。
updateProgress = (function(_this) {
return function(e) {
var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results;
if (e != null) {
progress = 100 * e.loaded / e.total;
for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
file = files[_j];
file.upload = {
progress: progress,
total: e.total,
bytesSent: e.loaded
};
}
} else {
allFilesFinished = true;
progress = 100;
for (_k = 0, _len2 = files.length; _k < _len2; _k++) {
file = files[_k];
if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) {
allFilesFinished = false;
}
file.upload.progress = progress;
file.upload.bytesSent = file.upload.total;
}
if (allFilesFinished) {
return;
}
}
_results = [];
for (_l = 0, _len3 = files.length; _l < _len3; _l++) {
file = files[_l];
_results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent));
}
return _results;
};
})(this);
這就是它如何分配給進行中的
progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
progressObj.onprogress = updateProgress;
那么它被稱為
updateProgress();
函數表達式僅用於創建作用域。 從IIFE(立即調用的函數表達式)返回的函數被分配給updateProgress
變量,因此最終結果基本上就像您具有帶有參數的常規函數一樣:
function updateProgress(e) {
var allFilesFinished, ...
...
return _results;
}
當updateProgress
用作事件處理程序時,它將以事件對象作為第一個參數來調用。 結束於e
參數。
如果在沒有值的情況下調用參數e
,則其值將undefined
。 這使代碼執行else
部分,即以100%顯示進度。
無論調用什么updateProgress
都會傳遞一個參數,然后可以通過e
引用該參數。
例:
updateProgress(42)
: e
現在將引用42
。
最有可能將updateProgress
用作事件處理程序,因此e
將引用事件對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.