0

I understand that function expressions must be expressed at the top if you want to use them vs function declarations which are hoisted to the top.

When I call my constructor from with window.onload, it works. However if I don't have a window.onload, and call my constructor before my function expression, the code breaks.

<script type="text/javascript">

        window.onload = function () {
            var c = new C();
        }  // this works, but if i delete window.onload the code breaks.

        var C = function () {
            console.log("test");

        };

 </script>
runners3431
  • 1,425
  • 1
  • 13
  • 30
  • 1
    The `var C` *declaration* is still hoisted, even though the function itself isn't. So execution goes: `var C` declared **=>** window `load` event listener is specified (but doesn't run yet – the window hasn't finished loading) **=>** function is assigned to `C` **=>** window `load` event fires (by which point your function has been assigned to `C`). – Shai Sep 10 '14 at 15:05
  • Be careful to read answers & comments in the QA I linked to (the accepted answer isn't very good) – Denys Séguret Sep 10 '14 at 15:05
  • Let's make a simpler but equivalent example: `var foo = function() { alert(bar); }; var bar = 42; foo();`. What do you think will happen here? Will the `alert` "work" correctly? – Felix Kling Sep 10 '14 at 15:10
  • 1
    @runners3431 To answer your question more directly: function expressions don't have to be expressed **at the top**, they have to be expressed **before you call them**. [The `window.onload` function is called when loading finishes](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload), i.e. **after** your function has been assigned to `C`. – Shai Sep 10 '14 at 15:15
  • [Concurrency model and Event Loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop) –  Sep 10 '14 at 15:31

2 Answers2

0

That's simple. window.onload executed later, when C is defined, if you just call new C it will throw because C is undefined.

Move your call after definition, or define it using 'function' keyword, not 'var'

Anatoliy
  • 29,485
  • 5
  • 46
  • 45
0

window.onload does not get fired immediately. It gets fired when the window is done loading.

What you are doing is saying "execute this function to create a new variable 'c' when the windows is done loading."

However since var C is defined in the global scope it gets assigned its function value immediately. So it is ready to be evaluated by the time window.load executes.

Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46