在 JavaScript 函数中定义全局变量

新手上路,请多包涵

是否可以在 JavaScript 函数中定义全局变量?

我想在其他函数中使用 trailimage 变量(在 makeObj 函数中声明)。

<html xmlns="http://www.w3.org/1999/xhtml">
    <head id="Head1" runat="server">
        <title></title>
        <script type="text/javascript">
            var offsetfrommouse = [10, -20];
            var displayduration = 0;
            var obj_selected = 0;
            function makeObj(address) {
                **var trailimage = [address, 50, 50];**
                document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0"  style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
                obj_selected = 1;
            }

            function truebody() {
                return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
            }
            function hidetrail() {
                var x = document.getElementById("trailimageid").style;
                x.visibility = "hidden";
                document.onmousemove = "";
            }
            function followmouse(e) {
                var xcoord = offsetfrommouse[0];
                var ycoord = offsetfrommouse[1];
                var x = document.getElementById("trailimageid").style;
                if (typeof e != "undefined") {
                    xcoord += e.pageX;
                    ycoord += e.pageY;
                }
                else if (typeof window.event != "undefined") {
                    xcoord += truebody().scrollLeft + event.clientX;
                    ycoord += truebody().scrollTop + event.clientY;
                }
                var docwidth = 1395;
                var docheight = 676;
                if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
                    x.display = "none";
                    alert("inja");
                }
                else
                    x.display = "";
                x.left = xcoord + "px";
                x.top = ycoord + "px";
            }

            if (obj_selected = 1) {
                alert("obj_selected = true");
                document.onmousemove = followmouse;
                if (displayduration > 0)
                    setTimeout("hidetrail()", displayduration * 1000);
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px;
            top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
        </form>
    </body>
</html>

原文由 hamze 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 847
2 个回答

正如其他人所说,您可以在全局范围内(在所有函数和模块之外)使用 var 来声明全局变量:

 <script>
 var yourGlobalVariable;
 function foo() {
 // ...
 }
 </script>

(请注意,这仅在 全局 范围内是正确的。如果该代码在模块中 - <script type="module">...</script> - 它不会在全局范围内,因此不会创建全球的。)

或者:

在现代环境中,您可以分配给 globalThis 引用的对象上的属性( globalThis 是在 ES2020 中添加的):

 <script>
 function foo() {
 globalThis.yourGlobalVariable = ...;
 }
 </script>

在浏览器上,你可以对全局调用 window 做同样的事情:

 <script>
 function foo() {
 window.yourGlobalVariable = ...;
 }
 </script>

…因为在浏览器中,所有用 var 声明的全局变量全局变量都是 window 对象的属性。 (在最新规范 ECMAScript 2015 中,全局范围内的新 letconstclass 语句创建不是全局对象属性的全局变量;ES2015 中的新概念。)

隐式全局变量也很可怕,但不要故意这样做,并尽量避免意外这样做,也许是通过使用 ES5 的 "use strict" 。)

所有这一切:如果可能的话,我会避免使用全局变量(而且几乎可以肯定)。正如我所提到的,它们最终成为 window 的属性,并且 window 已经 足够拥挤,所有带有 id 的元素(以及许多只有 name 的元素)都被转储在其中(并且不管即将推出的规范,IE 都会转储任何东西上面有 name )。

相反,在现代环境中,使用模块:

 <script type="module">
 let yourVariable = 42;
 // ...
 </script>

模块中的顶级代码位于模块范围内,而不是全局范围内,因此这会创建一个该模块中的所有代码都可以看到的变量,但这不是全局的。

在没有模块支持的过时环境中,将您的代码包装在一个作用域函数中并使用该作用域函数的本地变量,并使您的其他函数在其中闭包:

 <script>
 (function() { // Begin scoping function
 var yourGlobalVariable; // Global to your code, invisible outside the scoping function
 function foo() {
 // ...
 }
 })(); // End scoping function
 </script>

原文由 T.J. Crowder 发布,翻译遵循 CC BY-SA 4.0 许可协议

只需声明

var trialImage;

外部。然后

function makeObj(address) {
    trialImage = [address, 50, 50];
    ...
    ...
}

原文由 harihb 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题