在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>

#1楼

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

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

因为该函数是使用此参数全局调用的,所以这里是全局范围。 因此,事物应该是全球事物。


#2楼

UPDATE1:如果您阅读注释,则围绕此特定命名约定进行了很好的讨论。

UPDATE2:似乎自从我的答案发布以来,命名约定就变得更加正式了。 教书,写书等的人谈论var声明和function声明。

UPDATE3:这是支持我的观点的其他Wikipedia帖子: http : //en.wikipedia.org/wiki/Declaration_( computer_programming)#Declarations_and_Definitions

...并回答主要问题。 函数前的DECLARE变量。 这将起作用,并且将遵循在范围顶部声明变量的良好做法:)


#3楼

经典示例:

window.foo = 'bar';

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

;(function (root) {
    'use strict'

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

如今,还可以选择使用WebStorage API

localStorage.foo = 42;

要么

sessionStorage.bar = 21;

在性能方面,我不确定它是否比将值存储在变量中明显慢。

我可以使用...所述的广泛的浏览器支持


#4楼

    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 。 我的代码需要同样的东西,这确实是个好主意。


#5楼

这是一个可能很丰富的示例代码。

  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 

在这里,我找到了一个不错的答案: 如何在JavaScript中声明一个全局变量


#6楼

这是另一个使变量在其他函数中可用而又不必使用全局变量的简便方法:

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


#7楼

只需在函数外部声明它,然后在函数内部分配值即可。 就像是:

<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);

#8楼

只需声明

var trialImage;

外。 然后

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

希望这可以帮助。


#9楼

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

var trailimage;

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

#10楼

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

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

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

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

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

(也有隐式全局变量的恐怖 ,但不要故意这样做,并尽最大努力避免意外地这样做,也许可以使用ES5的"use strict" 。)

话虽如此:如果可能(我几乎可以肯定),我会避免使用全局变量。 正如我提到的那样,它们最终是window属性,并且window已经足够拥挤 ,所有具有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>

#11楼

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

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
      trailimage = [address, 50, 50];
      ....
}

#12楼

因此,您希望函数内部的变量在函数外部可用吗? 为什么不返回函数内部变量的结果? var x = function returnX { var x = 0; return x; } var x = function returnX { var x = 0; return x; }是这个主意...

    <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;
            return trailimage;
        }

        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>

我尚未对此进行测试,但是如果您的代码在进行此小更改之前就可以使用,那么它应该可以使用。

发布了0 篇原创文章 · 获赞 2 · 访问量 5928

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104058950