简体   繁体   English

在javascript中的函数中使用全局变量

[英]Using a global variable in a function in javascript

I want to define a variable (Boolean), and then use it in a function two times. 我想定义一个变量(布尔值),然后在函数中使用两次。 I started with defining a global variable, and then use this variable locally in my function as follows: 我先定义一个全局变量,然后在函数中本地使用此变量,如下所示:

var  inpLock = false;
…
function doSomething(inpLock) {
    inpLock = true;
    switch …
        case
        case
    inpLock = false;
}

What happens by running this is: it sets the variable to true but not back to false. 运行此命令会发生以下情况:将变量设置为true,但不设置为false。 If I declare the variable inside the function like: var inpLock it also won't work. 如果我在函数内部声明变量,例如:var inpLock,它也将不起作用。 Any help will be appreciated. 任何帮助将不胜感激。

Giving a name to a function argument ( doSomething(inpLock) ) declares a local variable of that name. 给函数参数命名( doSomething(inpLock) )将声明该名称的局部变量。

This masks any global variable with the same name. 这将屏蔽具有相同名称的所有全局变量。

Changes you make to the variable inside the function only touch the local variable and ignore the global. 您对函数内部变量所做的更改仅触摸局部变量而忽略全局变量。

Avoid reusing variable names in nested scopes. 避免在嵌套作用域中重用变量名。 It causes confusion. 它引起混乱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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