index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="Script1.js"></script>
<script src="Script2.js"></script>
</head>
<body>
</body>
</html>
Script1.js
var Main;
window.onload = Main;
Script2.js
function Main() {
alert("foo");
}
If I throw a breakpoint @ var Main; and step through the code in WebStorm, it appears to:
- Load Script1.js.
- Load Script2.js.
- Call
Main().
However it doesn't execute the statement alert("foo") in that function. Could someone explain what's going on in more detail?
- NOTE: I realize you should avoid using
onload. - NOTE: I realize I could re-order the scripts and it would show the alert.
- NOTE: If I omit the statement
var Main;, step 3 above does not occur.
Bonus: In WebStorm, it shows the value of the window.onload field as null and the value of Main as void. What is the difference between a value of null and void?
window.onloadhas been assigned the current value ofMainwhich isundefined.Mainis assigned towindow.onloadthatMainis stillvoid. However, when the second script loads, isn't it setting the value ofMainto the functionMain()and thus when thewindow.onloadevent fires,Mainis now no longervoidand instead refers to theMainfunction established as part of loading the second script?Mainis a function in the second script, but it doesn't change the fact thatwindow.onloadis set toundefined(notvoid,voidis not a value). The above comment is really the best answer here.onloadproperty would hold a reference to theMainvariable, and would observe its changes. But because it's a "by value" language, the valueundefinedis given to.onload, and.onloadis entirely unaware of what happens to theMainvariable thereafter.window.onloadshould be 'null'?