我不太确定<script>标记之间会发生什么。例如,以下内容提供了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>

但这有效:
<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>

最佳答案

上一个脚本在第一个示例中首先执行,因此尚不了解T,因此会出现错误。

在第二个示例中,在执行脚本标签后立即定义T,并在任何地方都知道T。这是由于函数声明被提升到顶部,无论顺序如何,它们始终可用。函数声明提升更深入地解释here

应用提升之后的第二个示例:

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

10-04 22:15
查看更多