是否可以在 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
不会声明全局变量。为未声明的变量赋值的结果是在全局对象上创建了一个属性,这与声明变量完全不同。
正如其他人所说,您可以在全局范围内(在所有函数和模块之外)使用 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 中,全局范围内的新 let
、const
和 class
语句创建了不是全局对象属性的全局变量;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>
只需声明
var trialImage;
外部。然后
function makeObj(address) {
trialImage = [address, 50, 50];
...
...
}
如果您阅读了评论,那么围绕这个特定的命名约定会有一个很好的讨论。
似乎自从我的答案发布以来,命名约定变得更加正式。教书、写书等的人谈论var
宣言和function
宣言。
这是支持我的观点的附加维基百科帖子:Declarations and definitions ...并回答主要问题。在函数之前声明变量。这将起作用,并且符合在范围顶部声明变量的良好做法:)
definition
和 declaration
的含义。您的第一行可以是声明或定义(取决于它的位置);第二个只是一个任务。声明仅指定标识符的解释(即 myVar
是 int
);如果声明 also 保留存储,则它是 definition
。这与打字无关;它是编译单元如何理解对其他编译单元的引用的一部分。
var myVar
也称为 declaration(不需要键入),而 myVar = 10
称为 assignment。我听说过化合物 (var myVar = 10;
) 的术语“定义”。
只需在函数外部声明它,并在函数内部赋值。就像是:
<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);
不,你不能。只需在函数外部声明变量即可。您不必在分配值的同时声明它:
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
window
的属性是同义词。无论哪种方式,您所做的语义区别都很明确,所以我不介意不赞成。编辑:无法更改我的投票,对不起!
var
,这就是 Guffa 的意思隐式创建(例如@DhruvPathak 也指出了那里)。
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")
来设置和获取变量。
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
}
}
经典例子:
window.foo = 'bar';
使用 IIFE 遵循最佳实践的现代安全示例:
;(function (root) {
'use strict'
root.foo = 'bar';
)(this));
如今,还可以选择使用 WebStorage API:
localStorage.foo = 42;
或者
sessionStorage.bar = 21;
性能方面,我不确定它是否比在变量中存储值明显慢。
Can I use... 中所述的广泛浏览器支持。
localStorage.foo = JSON.stringify({ arbitrary: 'object', meaning: 42, awesome: true });
和 var foo = JSON.decode(localStorage.foo);
。
localStorage
与全局变量有什么关系?
这很简单。在函数外部定义 trailimage
变量并在 makeObj 函数中设置其值。现在您可以从任何地方访问它的值。
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
...
}
是的你可以。只是不要使用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);
全局变量在函数外部声明,以便在整个程序中可访问,而局部变量使用 var 存储在函数中,仅在该函数的范围内使用。如果你声明一个变量而不使用 var,即使它在函数内部,它仍然会被视为全局变量。参考文献 = https://www.freecodecamp.org/news/global-variables-in-javascript-explained/
如果您希望函数内部的变量在函数外部可用,则返回函数内部变量的结果。
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>
我还没有对此进行测试,但是如果您的代码在进行小改动之前可以正常工作,那么它应该可以工作。
使用 window
对象不是一个好主意。正如我在评论中看到的,
'use strict';
function showMessage() {
window.say_hello = 'hello!';
}
console.log(say_hello);
这将引发错误,以使用我们需要首先调用 showMessage function
的 say_hello
变量。
所有声明的变量都没有“var”或“let”或前面的任何其他东西,如“const”,都是全局的。所以 ....
function myFunction(){
myVar = "value"; // myVar is a global variable and can be used anywhere inside <script> tags.
}
如果你正在创建一个启动函数,你可以这样定义全局函数和变量:
function(globalScope)
{
// Define something
globalScope.something()
{
alert("It works");
};
}(window)
因为这个函数是用这个参数全局调用的,所以这里是全局范围。所以,这个东西应该是一个全球性的东西。
this
在函数外处于严格模式下的 undefined
,不应用于引用全局对象。
这是可能有用的示例代码。
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?
这是使变量在其他函数中可用而无需使用全局变量的另一种简单方法:
function makeObj() { // var trailimage = 'test'; makeObj.trailimage = '测试'; } 功能 someOtherFunction() { document.write(makeObj.trailimage); } makeObj();一些其他功能();
window
在 Node.js 中不起作用。这里最简单的技巧是设置:GLOBAL.window = GLOBAL;
-- 如 in this related question 所述。当然,这在概念上并不漂亮。我更喜欢反过来做,所以我可以使用GLOBAL
而不是window
。window.yourGlobalVariable = ...;
在堆栈网站上阅读了 5 到 6 个问题后,效果就像一个魅力。eval
。而是:window[dynamic_variable_name] = dynamic_variable_value;