在 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>
(请注意,这仅在 全局 范围内成立.如果该代码在模块中 - - 它不会在全局范围内,因此不会创建全局.)
(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.)
或者:
在现代环境中,您可以为 globalThis
指的是(globalThis
是在 ES2020 中添加的):
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
已经是 足够拥挤 带有 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屋!