Define global variable inside a function

前提是你 提交于 2020-01-15 07:58:07

问题


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?


回答1:


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)




回答2:


You can assign it to the window-object:

function test() {
    window.globalvariable = 'something';
}



回答3:


Simply declare it outside of the function:

var testvar;

function test() {
    testvar = 1;
    //the rest of the code
}


来源:https://stackoverflow.com/questions/23215633/define-global-variable-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!