javascript通过脚本标签定义范围? [英] javascript defines scope by script tags?

查看:76
本文介绍了javascript通过脚本标签定义范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从未遇到过这个问题,也不知道为什么。
唯一的解释是范围问题。

Never met this problem, and don't know why. The only explanation is a scope issue.

在同一页面中,我有2个JS部分:

In the same page, I have 2 sections of JS :

...
 <script type="text/javascript">
    go();
  </script>

  <script type="text/javascript">
    function go()
    { alert('');  }
  </script>
...

这将显示错误: go未定义

其中

...
     <script type="text/javascript">
        go();

        function go()
        { alert('');  }
      </script>
    ...

正在运行(显然)。

< script> 标签是否会创建JS的范围?
help?

Does <script> tag creates a scope of JS ? help ?

推荐答案

这不是范围问题。如果在一个脚本元素中定义一个函数(在全局范围内),则可以在另一个脚本元素中使用它。

This isn't a scope issue. If you define a function (in the global scope) in one script element, then you can use it in another.

但是,脚本元素将按原样进行解析和执行遇到。

However, script elements are parsed and executed as they are encountered.

提升不适用于脚本元素。在较早的脚本元素的初始运行期间,在稍后的脚本元素中定义的函数将不可用。

Hoisting won't work across script elements. A function defined in a later script element won't be available during the initial run of an earlier script element.

您需要交换脚本元素的顺序,或延迟函数调用,直到定义它的脚本运行(例如将其附加到<$) c $ c> onload 事件处理程序。)

You either need to swap the order of your script elements, or delay the function call until after the script that defines it has run (e.g. by attaching it to an onload event handler).

<script>
    function go() {
        alert('');  
    }
</script>
<script>
    go();
</script>

<script>
    window.addEventListener("load", function () { 
        go();
    }, false);
</script>
<script>
    function go() {
        alert('');  
    }
</script>

这篇关于javascript通过脚本标签定义范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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