[英]Explain this JavaScript onload function
Here's an example for registering a function on document load (most of it taken from JavaScript: The Definitive Guide ): 这是一个在文档加载时注册函数的示例(大部分取自JavaScript:The Definitive Guide ):
"use strict";
//run function f when document is loaded
function onLoad(f) {
if (onLoad.loaded) // If already loaded
window.setTimeout(f, 0);
else if (window.addEventListener)
window.addEventListener("load", f, false);
}
onLoad.loaded = false;
onLoad(function() { onLoad.loaded = true; });
onLoad(myfunc);
function myfunc() {
console.log("Hello, world!");
}
I'm getting confused with the line onLoad(function() { onLoad.loaded = true; });
我对onLoad(function() { onLoad.loaded = true; });
行感到困惑onLoad(function() { onLoad.loaded = true; });
. 。 I can tell that it's self-invocation, but using the function name again baffles me. 我可以说这是自调用,但是再次使用函数名使我感到困惑。 Why is it needed? 为什么需要它? I find that if I do only (function() { onLoad.loaded = true; });
我发现如果我只做(function() { onLoad.loaded = true; });
then also the output is the same. 那么输出也一样。
Finally, I can get the same output by using: 最后,我可以使用以下命令获得相同的输出:
function myfunc() {
console.log("Hello, world!");
}
window.onload = (function() {window.setTimeout(myfunc, 0);});
How is my code better/worse? 我的代码如何更好/更糟糕?
Thanks in advance! 提前致谢!
I'm getting confused with the line
onLoad(function() { onLoad.loaded = true; });
我对onLoad(function() { onLoad.loaded = true; });
行感到困惑onLoad(function() { onLoad.loaded = true; });
. 。 I can tell that it's self-invocation, but using the function name again baffles me. 我可以说这是自调用,但是再次使用函数名使我感到困惑。
It isn't a self-invocation. 这不是一个自调用。
It is a call to the function onLoad
(previously defined) with one argument (which is a function expression). 它是使用一个参数(这是一个函数表达式)对函数onLoad
(先前定义)的调用。
Finally, I can get the same output by using… How is my code better/worse? 最后,我可以通过使用…获得相同的输出…我的代码如何更好/更糟糕?
Your code will: 您的代码将:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.