gpt4 book ai didi

带参数的javascript匿名函数调用

转载 作者:行者123 更新时间:2023-11-30 16:54:05 25 4
gpt4 key购买 nike

谁能解释一下匿名函数调用中的参数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);

这是它分配给 onprogress 的方式

 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%。

关于带参数的javascript匿名函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30016908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com