是否可以在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>

当前回答

不,你不能。只需在函数外部声明变量即可。你不必在赋值的同时声明它:

var trailimage;

function makeObj(address) {
  trailimage = [address, 50, 50];

其他回答

如果你正在创建一个启动函数,你可以这样定义全局函数和变量:

function(globalScope)
{
    // Define something
    globalScope.something()
    {
        alert("It works");
    };
}(window)

因为函数是通过这个参数全局调用的,所以这里是全局作用域。所以,这个东西应该是全球性的。

使用window对象不是一个好主意。正如我在评论中看到的,

'use strict';

function showMessage() {
    window.say_hello = 'hello!';
}

console.log(say_hello);

这将抛出一个使用say_hello变量的错误,我们需要首先调用showMessage函数。

只是声明

var trialImage;

在外面。然后

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

下面是示例代码,可能会有帮助。

var Human = function() {
    name = "Shohanur Rahaman";  // Global variable
    this.name = "Tuly"; // Constructor variable 
    var age = 21;
};

var shohan = new Human();

document.write(shohan.name + "<br>");
document.write(name);
document.write(age); // Undefined because it's a local variable 

在这里我找到了一个很好的答案:如何在JavaScript中声明全局变量?

JavaScript中有三种作用域:

全局作用域:变量在代码中可用。 块作用域:变量在特定区域内可用,就像函数一样。 局部作用域:变量在更特定的区域可用,如if语句

如果在变量名之前添加Var,那么它的作用域将确定其位置


例子:

var num1 = 18; // Global scope
function fun() {
  var num2 = 20; // Local (Function) Scope
  if (true) {
    var num3 = 22; // Block Scope (within an if-statement)
  }
}

num1 = 18; // Global scope
function fun() {
  num2 = 20; // Global Scope
  if (true) {
    num3 = 22; // Global Scope
  }
}