Javascript strange loading sequence

后端 未结 1 1453
不思量自难忘°
不思量自难忘° 2020-12-31 07:01

In the code below I expected to see the following sequence

1, 2, loaded 

but I get

1, loaded, 2

Why?

相关标签:
1条回答
  • 2020-12-31 07:47

    You forgot ; after window onload function expression. So it becomes:

    window.onload = function () {
        console.log('loaded');
    }(function() { console.log('1'); }())
    

    So onload function is immediately executed with a one parameter, which is a result of another IEFE. Hence

    function() { console.log('1'); }()
    

    is executed first, and immediately after that window.onload function expression. Then console.log('2') expression.

    Great example why it's important not to forget semicolons at the end of the lines.

    0 讨论(0)
提交回复
热议问题