如何“范围”在HTML文档中使用JavaScript的多个脚本标记? [英] How does "scope" work with multiple script tags for Javascript in an HTML document?

查看:77
本文介绍了如何“范围”在HTML文档中使用JavaScript的多个脚本标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太清楚< script> 标签之间发生了什么。例如,下面给出了Chrome中的引用错误和类型错误:

 < html> 
< head>
< script type =text / javascript>
T.prototype.test = function(){
document.write(a);
}
< / script>
< script type =text / javascript>
函数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);
}
函数T(){}
var v = new T();
v.test();
< / script>
< / head>
< body>
< / body>
< / html>


解决方案

第一个例子中,所以它不知道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();

这篇关于如何“范围”在HTML文档中使用JavaScript的多个脚本标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆