简体   繁体   English

Javascript全局与局部范围

[英]Javascript Global vs Local Scope

I'm currently trying to understand Javascript's interesting take on global vs local scope. 我目前正在尝试了解Javascript在全局范围还是局部范围方面的有趣观点。

My question is that why would the following returns undefined ? 我的问题是,为什么以下返回undefined

var a = 100;
function local() {
    if (false) {
        var a = 50;
    }
    alert(a);
}

Additionally, I ran this: 另外,我运行了这个:

var a = 100;
function local() {
    alert(a);
}

The result was a resounding: 100. 结果是惊人的:100。

Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript? 有什么方法可以指定何时要从全局范围获取变量,例如可以与Javascript一起使用的PHP 全局关键字?

Because of hoisting . 因为吊装

It means every variable declaration get's popped to the top of the function so the actual code that runs is: 这意味着将每个变量声明都弹出到函数顶部,因此运行的实际代码为:

var a = 100;
function local(){
    var a;
    if (false)
        a = 50;

    alert(a);
}

It has very little to do with global VS. 它与全局VS无关。 local, you simply hid the outer a variable with the inner a variable. 本地的,你只需躲在外a变量与内a变量。

Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript? 有什么方法可以指定何时要从全局范围获取变量,例如可以与Javascript一起使用的PHP全局关键字?

No 没有


Regarding the question in the comment "In the case that I want to revert to using a global variable in case the if condition fails (which I intentionally did), how can I do so? " : 关于注释中的问题“如果if条件失败(我故意这样做),我想恢复使用全局变量,该怎么办?”

You can use eval : 您可以使用eval

var a = 100;
function local() {
    if (false) {
        eval('var a = 50;');
    }
    alert(a);
}

Live DEMO 现场演示

But you should not! 但是你不应该!

JavaScript has function scope, not block scope (as many other programming languages). JavaScript具有功能范围,而不是块范围(与许多其他编程语言一样)。 That means regardless where the var statement occurs (in your case, an if-branch that is not even executed), it declares a variable a in the function's local scope. 这意味着无论var语句出现在何处(在您的情况下,if分支甚至都没有执行),它都会在函数的本地范围内声明变量a It shadows the global a variable, but since it has no value assigned it returns undefined . 它在全局变量中隐藏a变量,但是由于没有赋值,因此它返回undefined

Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript? 有什么方法可以指定何时要从全局范围获取变量,例如可以与Javascript一起使用的PHP全局关键字?

You can access the variable as a property of the global object ( window in browser environments): 您可以将变量作为全局对象的属性(浏览器环境中的window )进行访问:

var a = 100; // global
function loc() {
    var a = 50;
    alert(window.a); // 100
    alert(a); // 50
}
loc();

However, you will hardly use this. 但是,您几乎不会使用它。 Global variables are to be avoided in general, and in case of name clashes you should simply rename your local variable (for readability and maintainability at least). 通常应避免使用全局变量,并且在名称冲突的情况下,您应该简单地重命名本地变量(至少出于可读性和可维护性)。

I know that if a variable is in defined inside a function using var, then it will have Local Scope . 我知道,如果使用var在函数内部定义了变量,则它将具有Local Scope

I also know that any function has easy access to Global variable. 我也知道任何函数都可以轻松访问Global变量。

When I tested following in Console of Browser, first output was undefined . 当我在浏览器的控制台中测试以下内容时,第一个输出是undefined

It means that function nwf() was unable to access Global variable nw1 这意味着函数nwf()无法访问全局变量nw1

This is due to reference error which highlights importance of Strict Mode 这是由于参考错误突出显示了严格模式的重要性

To avoid such scenario, never re-declare and/or initialize any variable with same name inside and outside any function, just unlike following:- 为了避免出现这种情况,请不要在任何函数的内部和外部重新声明和/或初始化任何具有相同名称的变量,就像以下情况一样:

 var nw1 = 1; // var creates global scope outside function function nwf() { alert(nw1); var nw1 = 2; // var creates LOCAL scope inside function alert(nw1); }; nwf(); 

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

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