在JavaScript函数中定义全局变量 [英] Define a global variable in a JavaScript function
问题描述
是否可以在JavaScript函数中定义全局变量?
Is it possible to define a global variable in a JavaScript function?
我想在其他功能中使用trailimage
变量(在makeObj
函数中声明).
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>
推荐答案
正如其他人所说,您可以在全局范围内(在所有函数和模块之外)使用var
来声明全局变量:
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>
(请注意,这仅在 global 范围内是正确的.如果该代码在模块-<script type="module">...</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.)
或者:
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>
在浏览器上,您可以使用称为window
的全局变量来做同样的事情:
On browsers, you can do the same thing with the global called window
:
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
...由于在浏览器中,所有用全局变量是var
声明的全局变量window
对象的属性. (在最新规范ECMAScript 2015中,在全局范围内的新let
,const
和class
语句创建的不是全局对象属性的全局变量;这是ES2015中的新概念.)
...because in browsers, all global variables global variables declared with var
are properties of the window
object. (In the latest specification, ECMAScript 2015, the new let
, const
, and class
statements at global scope create globals that aren't properties of the global object; a new concept in ES2015.)
(还有隐式全局变量的恐怖 ,但不要故意这样做,并尽最大努力避免意外地这样做,也许可以使用ES5的"use strict"
.
(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"
.)
所有说明:如果可能(我几乎可以肯定),我会避免使用全局变量.正如我提到的,它们最终是window
的属性,而window
已经是 plenty 足够拥挤 ,其中所有带有id
(很多都带有name
)元素都被转储到其中(无论即将发布的规范如何,IE都将转储带有name
的几乎所有内容)在那儿).
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>
这篇关于在JavaScript函数中定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!