简体   繁体   English

解释此JavaScript onload函数

[英]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: 您的代码将:

  • Only support a function function to be called when the load event fires. 仅在加载事件触发时支持要调用的函数。 If you try to assign another function, it will overwrite the previous one instead of setting up two functions to be called when the event fires. 如果您尝试分配另一个函数,它将覆盖前一个函数,而不是设置事件触发时要调用的两个函数。
  • Won't call the function immediately (or at all) if the load event has already fired (so you can't use it in a script that can be dynamically added to the page as well as being used normally) 如果load事件已经触发,将不会立即(或根本不会)调用该函数(因此,您不能在可以动态添加到页面以及正常使用的脚本中使用它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM