在 JavaScript 函数中定义全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5786851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Define global variable in a JavaScript function
提问by hamze
Is it possible to define a global variable in a JavaScript function?
是否可以在 JavaScript 函数中定义全局变量?
I want use the trailimage
variable (declared in the makeObj
function) in other functions.
我想在其他函数中使用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>
回答by T.J. Crowder
Yes, as the others have said, you can use var
at global scope (outside of all functions) to declare a global variable:
是的,正如其他人所说,您可以var
在全局范围内(在所有函数之外)使用来声明一个全局变量:
<script>
var yourGlobalVariable;
function foo() {
// ...
}
</script>
Alternately, you can assign to a property on window
:
或者,您可以分配给以下属性window
:
<script>
function foo() {
window.yourGlobalVariable = ...;
}
</script>
...because in browsers, all global variablesglobal 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.)
...因为在浏览器中,所有用全局变量声明的全局变量var
都是window
对象的属性。(在最新的规范 ECMAScript 2015 中,全局范围内的 new let
、const
和class
语句创建了不是全局对象属性的全局变量;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"
.)
(还有隐式 globals 的可怕之处,但不要故意这样做,并尽量避免意外这样做,也许是使用 ES5 的"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 enoughwhat 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).
所有这一切都说:如果可能(而且几乎可以肯定),我会避免使用全局变量。正如我所说,他们最终会被的性能window
,并且window
已经大量拥挤够什么用的所有元素的id
(和许多只用name
),它被倾倒(且不论是即将到来的规范,IE转储只是用什么name
在那里)。
Instead, 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>
回答by op1ekun
UPDATE1: If you read the comments there's a nice discussion around this particular naming convention.
UPDATE1:如果你阅读了评论,有一个关于这个特定命名约定的很好的讨论。
UPDATE2: 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.
UPDATE2:似乎自从我的答案发布以来,命名约定变得更加正式。教书、写书等的人都在谈论var
宣言和function
宣言。
UPDATE3: Here is the additional wikipedia post that supports my point: http://en.wikipedia.org/wiki/Declaration_(computer_programming)#Declarations_and_Definitions
UPDATE3:这是支持我的观点的额外维基百科帖子:http: //en.wikipedia.org/wiki/Declaration_(computer_programming)#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 :)
...并回答主要问题。在您的函数之前声明变量。这将起作用,并且符合在范围顶部声明变量的良好做法:)
回答by harihb
Just declare
只需声明
var trialImage;
outside. Then
外部。然后
function makeObj(address) {
trialImage = [address, 50, 50];
..
..
}
Hope this helps.
希望这可以帮助。
回答by Guffa
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];
回答by DhruvPathak
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”也会使其成为全局变量,但最好在外部声明一次以获得更清晰的代码。这也将起作用:
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/
我希望这个例子能解释更多: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);
回答by Bharath
It is very simple define the trailimage variable outside the function and set its value in makeObj function. Now you can access its value from anywhere.
在函数外部定义 trailimage 变量并在 makeObj 函数中设置它的值非常简单。现在您可以从任何地方访问它的价值。
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
var trailimage;
function makeObj(address) {
trailimage = [address, 50, 50];
....
}
回答by ShanerM13
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 - Its 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;
I realize there is probably a lot of syntax errors in this but its the general idea... Thanks so much LayZee for pointing this out... You can find what a local and session Storage is at http://www.w3schools.com/html/html5_webstorage.asp. I have needed the same thing for my code and this was a really good idea.
我意识到这可能有很多语法错误,但它的总体思路...非常感谢 LayZee 指出这一点...您可以在http://www.w3schools找到本地和会话存储。 com/html/html5_webstorage.asp。我的代码需要同样的东西,这是一个非常好的主意。
回答by Lars Gyrup Brink Nielsen
Classic example:
经典例子:
window.foo = 'bar';
Modern, safe example following best practice by using an IIFE:
使用IIFE遵循最佳实践的现代安全示例:
;(function (root) {
'use strict'
root.foo = 'bar';
)(this));
Nowadays, there's also the option of using the WebStorage API
现在,还可以选择使用WebStorage API
localStorage.foo = 42;
or
或者
sessionStorage.bar = 21;
Performancewise, I'm not sure whether it is noticeably slower than storing values in variables.
性能方面,我不确定它是否比将值存储在变量中明显慢。
Widespread browser support as stated on Can I use...
广泛的浏览器支持,如Can I use...
回答by ShanerM13
So you want the variable inside the function available outside of the function? Why not return the results of the variable inside the function?
var x = function returnX { var x = 0; return x; }
is the idea...
所以你想让函数内的变量在函数外可用?为什么不返回函数内部变量的结果呢?
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>
I haven't tested this, but if your code worked prior to that small change, then it should work.
我还没有测试过这个,但是如果你的代码在那个小的更改之前工作,那么它应该工作。
回答by Shohanur Rahaman
Here is a sample code that might can be helful.
这是一个可能有用的示例代码。
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 cause its local variable
Here I found a nice answer How-can-one-declare-a-global-variable-in-JavaScript
在这里,我找到了一个很好的答案How-can-one-declare-a-global-variable-in-JavaScript