且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何“范围”在HTML文档中使用JavaScript的多个脚本标记?

更新时间:2023-01-08 16:28:59

第一个例子中,所以它不知道T还有错误。因此,在执行脚本标记后,T就会被很好地定义并且已知。这是由于函数声明被提升到顶端,无论命令是什么,它们总是可用的。 此处更深入地解释了函数声明提升

第二个例子是应用于吊装后:

  var v, 
T = function(){}; / *使用像这样的逗号是简短的:var v; var T = function(){}; * /

T.prototype.test = function(){
document.write(a);
};

v = new T();
v.test();


I'm not quite sure what goes on between <script> tags. For example, the following gives a reference error and type error in Chrome:

<html>
    <head>
    <script type="text/javascript">
        T.prototype.test = function() {
            document.write("a");
        }
    </script>
    <script type="text/javascript">
        function T() {}
        var v = new T();
        v.test();
    </script>
    </head>
    <body>
    </body>
</html>

But this works:

<html>
    <head>
    <script type="text/javascript">
    </script>
    <script type="text/javascript">
        T.prototype.test = function() {
            document.write("a");
        }
        function T() {}
        var v = new T();
        v.test();
    </script>
    </head>
    <body>
    </body>
</html>

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();