首页 文章

在JavaScript函数中定义全局变量

提问于
浏览
418

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

11 回答

  • -2

    是的,正如其他人所说,你可以在全局范围内使用 var (在所有函数之外)来声明一个全局变量:

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

    或者,您可以在 window 上分配属性:

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

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

    (还有the horror of implicit globals,但不要't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5' s "use strict" . )

    所有这一切:如果你可能的话,我会避免全局变量(你几乎可以肯定) . 正如我所提到的,它们最终成为 window 的属性,并且 window 已经plenty crowded enough所有带有 id (并且许多只有 name )的元素被转储(并且无论即将出现的规范,IE转储几乎所有 name 在那里) .

    相反,将代码包装在作用域函数中并使用该作用域函数的本地变量,并使其中的其他函数闭包:

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

    更新1:如果您阅读了这些评论,那么就围绕这个特定的命名约定进行了很好的讨论 .

    UPDATE2:似乎自从我的回答发布后,命名约定变得更加正式 . 教书,写书等的人都说 var 声明和 function 声明 .

    UPDATE3:这是支持我的观点的额外维基百科帖子:http://en.wikipedia.org/wiki/Declaration_(computer_programming)#Declarations_and_Definitions

    ......并回答主要问题 . 函数前的DECLARE变量 . 这将起作用,它将符合在范围顶部声明变量的良好实践:)

  • 640

    只是声明

    var trialImage;
    

    外 . 然后

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

    希望这可以帮助 .

  • 17

    不,你不能 . 只需在函数外声明变量即可 . 您不必在分配值的同时声明它:

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

    只需在函数外声明它,并在函数内部赋值 . 就像是:

    <script type="text/javascript">
        var offsetfrommouse = [10, -20];
        var displayduration = 0;
        var obj_selected = 0;
        var trailimage = null ;  // GLOBAL VARIABLE
        function makeObj(address) {
            trailimage = [address, 50, 50];  //ASSIGN VALUE
    

    或者简单地从函数内部的变量名中删除“var”也会使其成为全局变量,但最好将其声明为一次以获得更清晰的代码 . 这也有效:

    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    
    function makeObj(address) {
        trailimage = [address, 50, 50];  //GLOBAL VARIABLE , ASSIGN VALUE
    

    我希望这个例子能够解释更多:http://jsfiddle.net/qCrGE/

    var globalOne = 3;
    testOne();
    
    function testOne()
    {
        globalOne += 2;
        alert("globalOne is : " + globalOne );
        globalOne += 1;
    }
    
    alert("outside globalOne is : " + globalOne);
    
    testTwo();
    
    function testTwo()
    {
        globalTwo = 20;
        alert("globalTwo is " + globalTwo);
        globalTwo += 5;
    }
    
    alert("outside globalTwo is :" + globalTwo);
    
  • -1

    定义函数外部的trailimage变量并在makeObj函数中设置其值非常简单 . 现在,您可以从任何地方访问其值 .

    var offsetfrommouse = [10, -20];
    var displayduration = 0;
    var obj_selected = 0;
    var trailimage;
    function makeObj(address) {
          trailimage = [address, 50, 50];
          ....
    }
    
  • -2
    var Global = 'Global';
    
        function LocalToGlobalVariable() {
    
        //This creates a local variable.
    
        var Local = '5';
    
        //Doing this makes the variable available for one session
        //(a page refresh - Its the session not local)
    
        sessionStorage.LocalToGlobalVar = Local;
    
        // It can be named anything as long as the sessionStorage references the local variable.
        // Otherwise it won't work
        //This refreshes the page to make the variable take effect instead of the last variable set.
    
        location.reload(false);
        };
    
        //This calls the variable outside of the function for whatever use you want.
    
        sessionStorage.LocalToGlobalVar;
    

    我意识到这可能有很多语法错误,但它的一般想法......非常感谢LayZee指出这一点......你可以找到本地和会话存储在http://www.w3schools.com/html/html5_webstorage.asp . 我的代码需要相同的东西,这是一个非常好的主意 .

  • 12

    经典例子:

    window.foo = 'bar';
    

    使用IIFE遵循最佳实践的现代,安全示例:

    ;(function (root) {
        'use strict'
    
        root.foo = 'bar';
    )(this));
    

    如今,还有使用WebStorage API的选项

    localStorage.foo = 42;
    

    要么

    sessionStorage.bar = 21;
    

    Performancewise,我不确定它是否明显慢于在变量中存储值 .

    广泛的浏览器支持,如Can I use...所述

  • 8

    这是一个可能有用的示例代码 .

    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 cause its local variable
    

    在这里我找到了一个很好的答案How-can-one-declare-a-global-variable-in-JavaScript

  • 2

    如果您正在创建启动函数,则可以通过以下方式定义全局函数和变量:

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

    因为使用此参数全局调用该函数,所以这是全局范围 . 所以,这件事应该是一件全球性的事情 .

  • 10

    这是另一种简单的方法,可以在不使用全局变量的情况下使变量在其他函数中可用:

    function makeObj() {
      // var trailimage = 'test';
      makeObj.trailimage = 'test';
    }
    function someOtherFunction() {
      document.write(makeObj.trailimage);
    }
    
    makeObj();
    someOtherFunction();
    

相关问题