在JavaScript函数中定义全局变量

ham*_*mze 479 javascript variables scope declaration function

是否可以在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>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 711

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

<script>
var yourGlobalVariable;
function foo() {
    // ...
}
</script>
Run Code Online (Sandbox Code Playgroud)

或者,您可以在以下位置分配属性window:

<script>
function foo() {
    window.yourGlobalVariable = ...;
}
</script>
Run Code Online (Sandbox Code Playgroud)

...因为在浏览器中,声明的所有全局变量全局变量var都是window对象的属性.(在最新的规范中,ECMAScript 2015,全局范围内的new let,constclass语句创建的全局变量不是全局对象的属性;这是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>
Run Code Online (Sandbox Code Playgroud)

  • +1明确地将其声明为窗口是最易读的方式. (89认同)
  • 请注意,使用`window`将无法在Node中使用.这里最简单的技巧是设置:`GLOBAL.window = GLOBAL;` - 如[相关问题]中所述(http://stackoverflow.com/a/9590297/2228771).当然,它在概念上并不相当.我更喜欢以相反的方式做事,所以我可以使用`GLOBAL`代替`window`. (8认同)
  • @JacquesKoekemoer:没有理由在那里使用`eval`.相反:`window [dynamic_variable_name] = dynamic_variable_value;` (6认同)
  • `window.yourGlobalVariable = ...;` 在阅读堆栈站点上的 5 到 6 个问题后,效果非常好。 (5认同)
  • @CasparKleijne,我不明白.当你没有证据表明窗口对象确实存在时,为什么要在窗口上分配它.您对将来如何使用代码一无所知.它甚至可能在MongoDB环境或rino而不是您的节点中使用.如果你使用web worker,那么即使在浏览器中也不会看到window对象.这将彻底扼杀可重用性. (4认同)

op1*_*kun 19

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

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

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

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

  • 如果您想在其他地方定义变量,请务必了解吊装是什么.这是一篇非常好的文章http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting.祝好运! (7认同)
  • 即使在JS中,`var myVar`也被称为*声明*(它不需要输入)和`myVar = 10`和*赋值*.我听说过化合物的术语"定义"(`var myVar = 10;`). (3认同)
  • 这无助于回答问题。它应该是评论,而不是答案。 (2认同)
  • @Stuntddude你可能是对的:(我开始回答这个问题,然后决定有点分歧,这就是我们所得到的。仍有一些人仍然觉得它很有用,所以我把它留在这里。谢谢你回馈! (2认同)

har*_*ihb 14

只是声明

var trialImage;
Run Code Online (Sandbox Code Playgroud)

外.然后

function makeObj(address) {
    trialImage = [address, 50, 50];
..
..
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Dhr*_*hak 11

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

<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
Run Code Online (Sandbox Code Playgroud)

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

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;

function makeObj(address) {
    trailimage = [address, 50, 50];  //GLOBAL VARIABLE , ASSIGN VALUE
Run Code Online (Sandbox Code Playgroud)

我希望这个例子能够解释更多: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);
Run Code Online (Sandbox Code Playgroud)


Guf*_*ffa 11

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

var trailimage;

function makeObj(address) {
  trailimage = [address, 50, 50];
Run Code Online (Sandbox Code Playgroud)

  • @ mustafa.0x:你错了.您不能*在函数内定义*全局变量.您可以*隐式创建*全局变量,或在函数内创建*窗口属性*,但不能在函数内定义全局变量. (5认同)
  • **如果您不使用严格**(但为什么不使用严格?),[您实际上可以*可以*声明**并在函数内定义全局变量](http://stackoverflow.com / a / 3352033/274502),不遵循所有良好做法,只是不使用`var`,这就是Guffa暗中创建*的意思(例如@DhruvPathak也在此指出)。 (2认同)

小智 11

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)
  }
}
Run Code Online (Sandbox Code Playgroud)
num1 = 18; // Global scope
function fun() {
  num2 = 20; // Global Scope
  if (true) {
    num3 = 22; // Global Scope
  }
}
Run Code Online (Sandbox Code Playgroud)


Lar*_*sen 8

经典例子:

window.foo = 'bar';
Run Code Online (Sandbox Code Playgroud)

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

;(function (root) {
    'use strict'

    root.foo = 'bar';
)(this));
Run Code Online (Sandbox Code Playgroud)

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

localStorage.foo = 42;
Run Code Online (Sandbox Code Playgroud)

或者

sessionStorage.bar = 21;
Run Code Online (Sandbox Code Playgroud)

就性能而言,我不确定它是否比在变量中存储值明显慢。

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

  • OP正在寻找这个问题的解决方案:“我想在其他函数中使用trailimage变量(在makeObj函数中声明)。” 谁说解决方案必须涉及全局变量?全局变量很少能解决任何问题。 (2认同)

Bha*_*ath 5

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

var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;

function makeObj(address) {
    trailimage = [address, 50, 50];
    ...
}
Run Code Online (Sandbox Code Playgroud)


Sha*_*M13 5

    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 - it's 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;
Run Code Online (Sandbox Code Playgroud)

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

//编辑

截至(我相信)2015 年,引入了 javascript(如果您愿意)的新“标准”。该标准为 javascript 引入了许多新想法,其中之一就是范围的实现。

https://www.w3schools.com/js/js_scope.asp有关于这个想法的所有细节,但悬崖指出:

const 定义一个常数。

var 具有“全局”范围。

let 具有“功能”或“块”范围。


Gaw*_*ion 5

是的你可以。只是不要使用 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);
Run Code Online (Sandbox Code Playgroud)