Javascript奇怪的加载序列 [英] Javascript strange loading sequence

查看:63
本文介绍了Javascript奇怪的加载序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中我希望看到以下序列

In the code below I expected to see the following sequence

1, 2, loaded 

但我得到

1, loaded, 2

为什么?

<html>
<script>
window.onload = function()
{
    alert('loaded');
}

(function ()
{
    alert('1');
}());

(function ()
{
    alert('2');
}());

</script>
<body>
</body>
</html>


推荐答案

你忘了; 在窗口 onload 函数表达式之后。所以它变成:

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

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

所以 onload 函数立即执行一个参数,这是另一个IEFE的结果。因此

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

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

首先执行,然后立即执行 window.onload 函数表达式。然后 console.log('2')表达。

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.

这篇关于Javascript奇怪的加载序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆