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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top