ChatGPT解决这个技术问题 Extra ChatGPT

在 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>
声明一个全局的,不要使用“var”关键字
@Ibrahim:“要声明一个全局,不要使用“var”关键字” Gak! The Horror! ;-) 值得庆幸的是,严格模式消除了隐式全局变量。
@Ibrahim Diallo - 不使用 var 不会声明全局变量。为未声明的变量赋值的结果是在全局对象上创建了一个属性,这与声明变量完全不同。
此答案中的有用信息stackoverflow.com/a/4862268/1356098 :)

T
T.J. Crowder

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

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

(请注意,这仅适用于 global 范围。如果该代码在模块中 - <script type="module">...</script> - 它不会在全局范围内,因此不会创建全局。 )

或者:

在现代环境中,您可以分配给 globalThis 引用的对象的属性(在 ES2020 中添加了 globalThis):

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

在浏览器上,您可以使用名为 window 的全局变量执行相同的操作:

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

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

(也有 the horror of implicit globals,但不要故意这样做,尽量避免意外,可能使用 ES5 的 "use strict"。)

所有这一切:如果可能的话,我会避免使用全局变量(而且几乎可以肯定)。正如我所提到的,它们最终成为 window 的属性,并且 window 已经是 plenty crowded enough,所有带有 id 的元素(以及许多只有 name 的元素)都被倾倒在其中(并且不管即将推出的规范,IE 转储几乎所有带有 name 的内容)。

相反,在现代环境中,使用模块:

<script type="module">
let yourVariable = 42;
// ...
</script>

模块中的顶级代码位于模块范围内,而不是全局范围内,因此这会创建一个该模块中的所有代码都可以看到的变量,但这不是全局的。

在没有模块支持的过时环境中,将您的代码包装在一个作用域函数中并使用该作用域函数的本地变量,并使您的其他函数在其中闭包:

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

请注意,使用 window 在 Node.js 中不起作用。这里最简单的技巧是设置:GLOBAL.window = GLOBAL; -- 如 in this related question 所述。当然,这在概念上并不漂亮。我更喜欢反过来做,所以我可以使用 GLOBAL 而不是 window
@CasparKleijne,我不明白。当您实际上没有证据表明窗口对象确实存在时,为什么要在窗口上分配它。您对将来如何使用您的代码一无所知。它甚至可能用于 MongoDB 环境或 rino 而不是您的节点。如果您使用网络工作者,即使在浏览器中,窗口对象也是不可见的。这将完全扼杀可重用性。
window.yourGlobalVariable = ...; 在堆栈网站上阅读了 5 到 6 个问题后,效果就像一个魅力。
@JacquesKoekemoer:没有任何理由在那里使用 eval 。而是:window[dynamic_variable_name] = dynamic_variable_value;
@AstritSpanca - 这就是我在答案中间的括号中提到的Horror of Implicit Globals。 :-)
P
Peter Mortensen

只需声明

var trialImage;

外部。然后

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

P
Peter Mortensen

如果您阅读了评论,那么围绕这个特定的命名约定会有一个很好的讨论。

似乎自从我的答案发布以来,命名约定变得更加正式。教书、写书等的人谈论var宣言和function宣言。

这是支持我的观点的附加维基百科帖子:Declarations and definitions ...并回答主要问题。在函数之前声明变量。这将起作用,并且符合在范围顶部声明变量的良好做法:)


如果您想在别处定义变量,请务必了解提升是什么。这是一篇关于它的非常好的文章adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting。祝你好运!
这不是 C 中 definitiondeclaration 的含义。您的第一行可以是声明或定义(取决于它的位置);第二个只是一个任务。声明仅指定标识符的解释(即 myVarint);如果声明 also 保留存储,则它是 definition。这与打字无关;它是编译单元如何理解对其他编译单元的引用的一部分。
即使在 JS 中,var myVar 也称为 declaration(不需要键入),而 myVar = 10 称为 assignment。我听说过化合物 (var myVar = 10;) 的术语“定义”。
这无助于回答问题。它应该是评论,而不是答案。
@Stuntddude你可能是对的:(我开始回答这个问题,然后决定有点分歧,这就是我们所拥有的。仍然有些人觉得它很有用,所以我把它留在这里。谢谢你反馈!
P
Peter Mortensen

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

<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
G
Guffa

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

var trailimage;

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

对不起! “是否可以在 JavaScript 函数中定义全局变量?” - 正如第一个答案所示,“不,你不能”是不正确的!
@mustafa.0x:你错了。您不能在函数内定义全局变量。您可以隐式创建全局变量,或在函数内创建窗口属性,但不能在函数内定义全局变量。
对于浏览器环境中的 JavaScript,全局变量和 window 的属性是同义词。无论哪种方式,您所做的语义区别都很明确,所以我不介意不赞成。编辑:无法更改我的投票,对不起!
如果您不使用 strict(但您为什么不使用 strict?),you actually can declare and define global vars inside a function 违反所有良好做法,只是不使用 var,这就是 Guffa 的意思隐式创建(例如@DhruvPathak 也指出了那里)。
S
Shmack
    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;

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

//编辑

截至(我相信)2015 年,引入了一个新的 javascript“标准”(如果你愿意的话)。该标准为 javascript 引入了许多新思想,其中之一就是作用域的实现。

https://www.w3schools.com/js/js_scope.asp 包含有关此想法的所有详细信息,但悬崖指出:

const 定义一个常数。

var 具有“全局”范围。

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


到目前为止,这是唯一有效的答案,但它需要重新加载页面并且 location.reload(false); 会反复刷新页面。
在我的情况下,我将 sessionStorage 替换为 localStorage,这抑制了对 function LocalToGlobalVariable() 的需要。我使用 localStorage.setItem("xxx", "yyy")localStorage.getItem("xxx") 来设置和获取变量。
V
ViRuSTriNiTy

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

num1 = 18; // Global scope
function fun() {
  num2 = 20; // Global Scope
  if (true) {
    num3 = 22; // Global Scope
  }
}

P
Peter Mortensen

经典例子:

window.foo = 'bar';

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

;(function (root) {
    'use strict'

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

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

localStorage.foo = 42;

或者

sessionStorage.bar = 21;

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

Can I use... 中所述的广泛浏览器支持。


localStorage 和 sessionStorage 仅适用于字符串值。
没错,@HereToLearn_,但是您可以使用 localStorage.foo = JSON.stringify({ arbitrary: 'object', meaning: 42, awesome: true });var foo = JSON.decode(localStorage.foo);
localStorage 与全局变量有什么关系?
OP 正在寻找解决此问题的方法:“我想在其他函数中使用 trailimage 变量(在 makeObj 函数中声明)。”谁说解决方案必须涉及全局变量?全局变量很少是解决任何问题的好方法。
P
Peter Mortensen

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

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

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

G
Gawrion

是的你可以。只是不要使用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);

S
Shrey Mittal

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


P
Peter Mortensen

如果您希望函数内部的变量在函数外部可用,则返回函数内部变量的结果。

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>

我还没有对此进行测试,但是如果您的代码在进行小改动之前可以正常工作,那么它应该可以工作。


P
Peter Mortensen

使用 window 对象不是一个好主意。正如我在评论中看到的,

'use strict';

function showMessage() {
    window.say_hello = 'hello!';
}

console.log(say_hello);

这将引发错误,以使用我们需要首先调用 showMessage functionsay_hello 变量。


u
user3777368

所有声明的变量都没有“var”或“let”或前面的任何其他东西,如“const”,都是全局的。所以 ....

function myFunction(){

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

}

P
Peter Mortensen

如果你正在创建一个启动函数,你可以这样定义全局函数和变量:

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

因为这个函数是用这个参数全局调用的,所以这里是全局范围。所以,这个东西应该是一个全球性的东西。


this 在函数外处于严格模式下的 undefined,不应用于引用全局对象。
P
Peter Mortensen

这是可能有用的示例代码。

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 

在这里我找到了一个不错的答案:How can one declare a global variable in JavaScript?


虽然这在理论上可以回答问题,但it would be preferable在此处包含答案的基本部分,并提供链接以供参考。
a
am2124429

这是使变量在其他函数中可用而无需使用全局变量的另一种简单方法:

function makeObj() { // var trailimage = 'test'; makeObj.trailimage = '测试'; } 功能 someOtherFunction() { document.write(makeObj.trailimage); } makeObj();一些其他功能();