简体   繁体   中英

Define global variable inside a function

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)

You can assign it to the window-object:

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

Simply declare it outside of the function:

var testvar;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM