Referencing a JavaScript value before it is declared - can someone explain this

前端 未结 3 996
予麋鹿
予麋鹿 2020-11-27 16:31

I\'m hoping someone can explain to me why the below JavaScript/HTML will show \"door #2\" when the HTML is viewed in a browser:



        
相关标签:
3条回答
  • 2020-11-27 16:55

    The reason #3 doesn't change window.onload is that functions are called by reference, not by name. When you set window.onload = testprint, it assigns reference to the current value of testprint (door #2, as explained by CMS) to window.onload. Changing testprint's value later doesn't affect window.onload's value.

    Door #4 doesn't override door #2 (unless, as you said, you move it to the first script block) because it's in a different script block, so it gets parsed after the first block is completed.

    0 讨论(0)
  • 2020-11-27 16:59

    function testprint is global to the page. the testprint = function... assigns a variable, that I'm not sure exactly the entire scope of, but I get the idea that it's not added to the function table dictionary the way the first one is.

    0 讨论(0)
  • 2020-11-27 17:07

    Function declarations are subject of hoisting, and they are evaluated at parse time, by hoisting means that they are available to the entire scope in where they were declared, for example:

    foo(); // alerts foo
    foo = function () { alert('bar')};
    function foo () { alert('foo');}
    foo(); // alerts bar
    

    The first call to foo will execute the function declaration, because at parse time it was made available, the second call of foo will execute the function expression, declared at run-time.

    For a more detailed discussion about the differences between function expressions and function declarations, check this question and this article.

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