如何将局部变量变成全局变量?JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27887884/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:51:04  来源:igfitidea点击:

How to make a local variable into Global? JavaScript

javascript

提问by MThead

How can I make a local variable inside a function into global in Javascript.

如何在 Javascript 中将函数内的局部变量变为全局变量。

P.S Just pure JavaScript, no jQuery.
P.P.S. Nothing toooo complicated, thanks. :)

PS 只是纯 JavaScript,没有 jQuery。
PPS 没什么太复杂的,谢谢。:)

回答by matcartmill

You can do the following to access a global inside of a function.

您可以执行以下操作来访问函数内部的全局变量。

Any variable created outside the scope of a function can be reference inside of a function.

在函数作用域之外创建的任何变量都可以在函数内部引用。

Var myGlobalVar;

Function myFunction(){
   if(....) {
        myGlobalVar = 1;
   }
}

回答by Fábio Santos

You don't.

你没有。

You can copya local variable to the global scope by doing window.myVar = myVar(replacing windowby whatever is your global object), but if you reassign the local one, the global copy won't follow.

您可以通过执行(替换为您的全局对象的任何内容)局部变量复制到全局范围,但是如果您重新分配本地变量,则不会跟随全局副本。window.myVar = myVarwindow

回答by Mritunjay

You can assign a key to windowobject. It'll be a global variable.

您可以为window对象分配一个键。这将是一个全局变量。

function foo(){
   var bar1; //local variable
   bar1 = 11;
   window.bar2 = bar1; //bar2 will be global with same value.
}

OR

或者

In pure javascript if you will declare a variable without varanywhere, it will be in global scope.

在纯 javascript 中,如果你要声明一个没有var任何地方的变量,它将在全局范围内。

function foo(){
   var bar1; //local variable
   bar1 = 11;
   bar2 = bar1; //bar2 will be global with same value.
}

Note:-In the above text if bar2won't be declared yet, it will go to windowscope, otherwise it will just update the bar2. If you want to make sure about a global one say like window.bar2=bar1.

注意:-在上面的文本中,如果bar2尚未声明,它将进入window作用域,否则只会更新bar2. 如果你想确定一个全局的,比如window.bar2=bar1.