How does “scope” work with multiple script tags for Javascript in an HTML document?

前端 未结 2 690
甜味超标
甜味超标 2020-12-05 18:02

I\'m not quite sure what goes on between

相关标签:
2条回答
  • 2020-12-05 18:56

    The upper script is executed first in the first example, so it doesn't know about T yet, hence the error.

    In the second example, T is well defined and known anywhere as soon as the script tag is executed. This is due to function declarations being hoisted to the top, no matter what the order is, they are always available. Function declaration hoisting is more deeply explained here

    The second example after hoisting is applied:

    var v,
       T = function(){}; /* using comma like this is short-hand for: var v; var T = function(){}; */
    
    T.prototype.test = function() {
            document.write("a");
        };
    
    v = new T();
    v.test();
    
    0 讨论(0)
  • 2020-12-05 18:56

    They are each parsed in the global context, but in order. The entire first script tag is parsed and executed before the second one is considered. As part of parsing a script, function declarations are recognized ahead of time, which is why the second one works while the first one doesn't.

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