在函数内定义全局变量 [英] Define global variable inside a function
本文介绍了在函数内定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如 -
in python
def testFunc():
全局testVar
testVar + = 1
code>
是否有一种方法可以在函数中定义javascript中的testvar全局变量?
var 关键字即可。
解决方案 code> function testFunc(){
testVar = 1; //`testVar`现在是全局变量
}
注意:在你的代码的Python版本中,你不是定义一个全局变量。您引用了全局范围中定义的变量 testVar
。 var
MDN文档,
将值赋给未声明的变量隐式声明它为全局变量(它现在是全局对象的属性)
Like python is it possible to define global variable inside a function ?
for eg -
in python
def testFunc():
global testVar
testVar += 1
is there a way to define testvar global in javascript inside a function?
解决方案
Simply ignore the var
keyword.
function testFunc() {
testVar = 1; // `testVar` is a Global variable now
}
Note: In the Python version of your code, you are not defining a global variable. You are referring the variable testVar
defined in the global scope.
Quoting from var
MDN Docs,
assigning a value to an undeclared variable implicitly declares it as a global variable (it is now a property of the global object)
这篇关于在函数内定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文