Define global variable in a JavaScript function

2018-12-31 03:56发布

Is it possible to define a global variable in a JavaScript function?

I want use the trailimage variable (declared in the makeObj function) in other functions.

<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楼-- · 2018-12-31 04:08

Classic example:

window.foo = 'bar';

Modern, safe example following best practice by using an IIFE:

;(function (root) {
    'use strict'

    root.foo = 'bar';
)(this));

Nowadays, there's also the option of using the WebStorage API

localStorage.foo = 42;

or

sessionStorage.bar = 21;

Performancewise, I'm not sure whether it is noticeably slower than storing values in variables.

Widespread browser support as stated on Can I use...

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 04:13
    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;

I realize there is probably a lot of syntax errors in this but its the general idea... Thanks so much LayZee for pointing this out... You can find what a local and session Storage is at http://www.w3schools.com/html/html5_webstorage.asp. I have needed the same thing for my code and this was a really good idea.

查看更多
何处买醉
4楼-- · 2018-12-31 04:18

UPDATE1: If you read the comments there's a nice discussion around this particular naming convention.

UPDATE2: It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books etc. speak about var declaration, and function declaration.

UPDATE3: Here is the additional wikipedia post that supports my point: http://en.wikipedia.org/wiki/Declaration_(computer_programming)#Declarations_and_Definitions

...and to answer the main question. DECLARE variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

查看更多
泛滥B
5楼-- · 2018-12-31 04:22

if you are making a startup function, you can define global functions and variables in such way:

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

Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 04:23

It is very simple define the trailimage variable outside the function and set its value in makeObj function. Now you can access its value from anywhere.

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
      trailimage = [address, 50, 50];
      ....
}
查看更多
人气声优
7楼-- · 2018-12-31 04:26

Here is a sample code that might can be helful.

  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 

Here I found a nice answer How-can-one-declare-a-global-variable-in-JavaScript

查看更多
登录 后发表回答