在 JavaScript 函数中定义全局变量

发布于 2024-11-03 05:34:23 字数 2883 浏览 1 评论 0原文

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

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

開玄 2024-11-10 05:34:23

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

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

请注意,这仅在 global 范围内有效如果该代码位于模块中 -  - 它不会在全局范围内,因此不会不创建全局。)

或者:

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

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

在浏览器上,您可以使用全局称为window

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

...因为在浏览器中,使用var声明的所有全局变量全局变量都是window的属性代码>对象。 (全局范围内的新 letconstclass 语句[在 ES2015 中添加]创建的全局变量不是全局对象的属性;ES2015 中的一个新概念。)

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

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

As the others have said, you can use var at global scope (outside of all functions and modules) to declare a global variable:

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

(Note that that's only true at global scope. If that code were in a module — <script type="module">...</script> — it wouldn't be at global scope, so that wouldn't create a global.)

Alternatively:

In modern environments, you can assign to a property on the object that globalThis refers to (globalThis was added in ES2020):

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

On browsers, you can do the same thing with the global called window:

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

...because in browsers, all global variables global variables declared with var are properties of the window object. (The new let, const, and class statements [added in ES2015] at global scope create globals that aren't properties of the global object; a new concept in ES2015.)

(There's also the horror of implicit globals, but don't do it on purpose and do your best to avoid doing it by accident, perhaps by using ES5's "use strict".)

All that said: I'd avoid global variables if you possibly can (and you almost certainly can). As I mentioned, they end up being properties of window, and window is already plenty crowded enough what with all elements with an id (and many with just a name) being dumped in it (and regardless that upcoming specification, IE dumps just about anything with a name on there).

Instead, in modern environments, use modules:

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

The top level code in a module is at module scope, not global scope, so that creates a variable that all of the code in that module can see, but that isn't global.

In obsolete environments without module support, wrap your code in a scoping function and use variables local to that scoping function, and make your other functions closures within it:

<script>
(function() { // Begin scoping function
    var yourGlobalVariable; // Global to your code, invisible outside the scoping function
    function foo() {
        // ...
    }
})();         // End scoping function
</script>
溺ぐ爱和你が 2024-11-10 05:34:23

就对外声明一下吧

var trialImage;

。然后

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

Just declare

var trialImage;

outside. Then

function makeObj(address) {
    trialImage = [address, 50, 50];
    ...
    ...
}
晨曦慕雪 2024-11-10 05:34:23

如果您阅读评论,就会发现有关此特定命名约定的精彩讨论。

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

以下是支持我的观点的附加维基百科帖子:声明和定义
...并回答主要问题。在函数之前声明变量。这将会起作用,并且符合在作用域顶部声明变量的良好实践:)

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

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.

Here is the additional Wikipedia post that supports my point: 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 :)

北恋 2024-11-10 05:34:23

只需在函数外部声明它,并在函数内部赋值即可。比如:

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

Just declare it outside the functions, and assign values inside the functions. Something like:

<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

Or simply removing "var" from your variable name inside function also makes it global, but it is better to declare it outside once for cleaner code. This will also work:

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

function makeObj(address) {
    trailimage = [address, 50, 50];  // Global variable, assign value

I hope this example explains more: 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);
殤城〤 2024-11-10 05:34:23

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

var trailimage;

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

No, you can't. Just declare the variable outside the function. You don't have to declare it at the same time as you assign the value:

var trailimage;

function makeObj(address) {
  trailimage = [address, 50, 50];
长伴 2024-11-10 05:34:23

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

There are three types of scope in JavaScript:

  • Global Scope: where the variable is available through the code.
  • Block Scope: where the variable is available inside a certain area like a function.
  • Local Scope: where the variable is available in more certain areas, like an if-statement

If you add Var before the variable name, then its scope is determined where its location is


Example:

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
  }
}
贵在坚持 2024-11-10 05:34:23

这取决于您对“全球”一词的意图。如果您希望变量具有全局作用域以供函数使用(这正是OP想要的),那么您应该在编辑后阅读。如果您想在不使用服务器的情况下在页面之间重用数据,则应该考虑使用 sessionStorage


会话存储

    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;

这只是一般的想法。


范围

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

W3Schools 拥有有关此想法的所有详细信息,但悬崖注释:

const 定义了一个常量。
var 具有“全局”范围。
let 具有“函数”或“块”范围。

编辑 - 根据 Johny Why 的评论:

来自 w3schools

在函数内部声明时,

varletconst 非常相似。
它们都有函数作用域。


参考文献

Web 存储
范围

It depends on what you intend by the word "global". If you want global scope on a variable for function use (which is what the OP wants) then you should read after the edit. If you want to reuse data from page to page without the use of a server, you should be looking to you use sessionStorage.


Session Storage

    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;

This but its the general idea.


Scope

As of (I believe) 2015, a new "standard" for javascript (if you will) was introduced. This standard introduced many new ideas into javascript, one of them being the implementation of scope.

W3Schools has all the details concerning this idea, but the cliff notes:

const defines a constant.
var has "global" scope.
let has "function" or "block" scope.

EDIT - Per Johny Why's comment:

From w3schools

var, let and const are quite similar when declared inside a function.
They all have Function Scope.


References

Web Storage
Scope

找个人就嫁了吧 2024-11-10 05:34:23

经典示例:

window.foo = 'bar';

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

;(function (root) {
    'use strict'

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

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

localStorage.foo = 42;

sessionStorage.bar = 21;

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

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

Classic example:

window.foo = 'bar';

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

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

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

番薯 2024-11-10 05:34:23

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

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

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

It is very simple. Define the trailimage variable outside the function and set its value in the 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];
    ...
}
花间憩 2024-11-10 05:34:23

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

Yes, You can. Just don't use var, don't use let. Just initialize variable and it will be automaticly assigned global:

    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);
七堇年 2024-11-10 05:34:23

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

Global variables are declared outside of a function for accessibility throughout the program, while local variables are stored within a function using var for use only within that function’s scope. If you declare a variable without using var, even if it’s inside a function, it will still be seen as global.
References = https://www.freecodecamp.org/news/global-variables-in-javascript-explained/

一口甜 2024-11-10 05:34:23

所有没有“var”或“let”或前面的任何其他内容(例如“const”)声明的变量都是全局变量。所以 ....

function myFunction(){

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

}

All variables declared without "var" or "let" or anything else preceding it like "const" are global. So ....

function myFunction(){

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

}
予囚 2024-11-10 05:34:23

作为全局变量的替代方案,您可以使用浏览器的本地存储(如果不使用旧版本)。您最多可以使用 5MB 的此存储空间。
该代码将是,

var yourvariablevalue = 'this is a sample value';
localStorage.setItem("yourKeyvariablename", yourvariablevalue);

并且可以随时检索,即使在您离开并在其他时间打开它之后也是如此。

var yourvariablevalue = localStorage.getItem("yourKeyvariablename");

希望这对您有帮助!

As an alternative to global vars, you may use the localstorage of browsers (if not using older versions). You can use upto 5MB of this storage.
The code would be

var yourvariablevalue = 'this is a sample value';
localStorage.setItem("yourKeyvariablename", yourvariablevalue);

and this can be retrieved any time, even after you leave and open it at another time.

var yourvariablevalue = localStorage.getItem("yourKeyvariablename");

Hope this would help you !

一萌ing 2024-11-10 05:34:23

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

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

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

If you are making a startup function, you can define global functions and variables this 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.

蓝海似她心 2024-11-10 05:34:23

以下是示例代码,可能会有所帮助。

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 

在这里我找到了一个很好的答案:如何在 JavaScript 中声明全局变量?

Here is sample code that might can be helpful.

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 

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

浊酒尽余欢 2024-11-10 05:34:23

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

'use strict';

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

console.log(say_hello);

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

To use the window object is not a good idea. As I see in comments,

'use strict';

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

console.log(say_hello);

This will throw an error to use the say_hello variable we need to first call the showMessage function.

热鲨 2024-11-10 05:34:23

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

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

makeObj();
someOtherFunction();

Here is another easy method to make the variable available in other functions without having to use global variables:

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

makeObj();
someOtherFunction();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文