是否可以在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”或“let”或任何前面的东西,如“const”,都是全局变量。所以…

function myFunction(){

     myVar = "value"; // myVar is a global variable and can be used anywhere inside <script> tags.

}

其他回答

全局变量在函数外部声明,以便在整个程序中访问,而局部变量存储在函数中,使用var,仅在该函数的作用域内使用。如果你声明一个变量没有使用var,即使它在函数中,它仍然会被视为全局变量。 参考资料= https://www.freecodecamp.org/news/global-variables-in-javascript-explained/

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

var trailimage;

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

是的,你可以。不要用var,不要用let。只需初始化变量,它将自动被分配为全局:

    function firstFunction() {
        if (typeof(testVar) === "undefined") {testVar = 1;} //initializing variable if not initialized
        testVar += 1;
        console.log('Test variable inside 1st function: '+testVar);
    }
    function secondFunction() {
        testVar += 1;
        console.log('Test variable inside 2nd function: '+testVar);
    } 
    firstFunction();
    secondFunction();
    testVar += 1;
    console.log('Test variable outside: '+testVar);

作为全局变量的替代方案,您可以使用浏览器的localstorage(如果不使用旧版本)。您最多可以使用5MB的存储空间。 代码是

var yourvariablevalue = 'this is a sample value';
localStorage.setItem("yourKeyvariablename", yourvariablevalue);

它可以在任何时候被取回,甚至在你离开并在其他时间打开它之后。

var yourvariablevalue = localStorage.getItem("yourKeyvariablename");

希望这对你有所帮助!

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

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中声明全局变量?