简体   繁体   English

了解Javascript中的全局和本地范围

[英]Understanding Global & Local Scope in Javascript

I've been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov 我一直在使用Stoyan Stefanov使用面向对象的JavaScript学习Javascript

He offers an example comparing global and local scope: 他提供了一个比较全局和本地范围的示例:

var a = 123;
function f() {
    alert(a);
    var a = 1;
    alert(a);
}
f();

Looking at this example, I expected the first alert to be '123' and the second alert to be '1'. 看看这个例子,我预计第一个警报为'123',第二个警报为'1'。 Lo and behold, Stoyan says: 瞧,斯托扬说:

You might expect that the first alert() will display 123 (the value of the global variable a) and the second will display 1 (the local a). 您可能希望第一个alert()将显示123(全局变量a的值),第二个将显示1(本地a)。 This is not the case. 不是这种情况。 The first alert will show “undefined”. 第一个警报将显示“未定义”。 This is because inside the function the local scope is more important than the global scope. 这是因为在函数内部,局部范围比全局范围更重要。 So a local variable overwrites any global variable with the same name. 因此局部变量会覆盖具有相同名称的任何全局变量。 At the time of the first alert() a was not yet defined (hence the value undefined) but it still existed in the local space. 在第一个alert()时,a尚未定义(因此值未定义),但它仍然存在于本地空间中。

The explanation was not clear to me, how can the local variable overwrite the global variable in the first alert? 我的解释并不清楚,局部变量如何在第一个警报中覆盖全局变量? Any other/different explanations would be appreciated. 任何其他/不同的解释将不胜感激。

It is not overriding the global variable. 它不会覆盖全局变量。 What is happening is called "variable hoisting". 发生的事情被称为“可变吊装”。 That is, a var a; 即, var a; gets inserted at the top of the function. 插入函数的顶部。

The script engine changes your script to be the following: 脚本引擎将脚本更改为以下内容:

var a = 123;
function f() {
    var a;
    alert(a);
    a = 1;
    alert(a);
}
f();

Lesson to learn: Always declare your variables before you use them. 需要学习的经验:在使用之前始终声明变量。 Some will say declare all your variables at the top of the function. 有些人会说在函数顶部声明所有变量。

In simple words, all the declarations, of both variables and functions are considered first. 简单来说,首先考虑变量和函数的所有声明。 So local var a in effect will override global variable only in local scope and will have no value ie undefined . 因此局部var a实际上将仅在局部范围中覆盖全局变量,并且没有值,即undefined So first alert will show undefined . 因此,第一个警报将显示undefined Second alert will show 1 as it is after a = 1 . a = 1之后,第二个警报将显示a = 1 This just happens locally and global variable a will have value 123 - it won't be changed. 这只是在本地发生,全局变量a将具有值123 - 它不会被更改。

another example using function to show how it works 另一个使用函数来展示它如何工作的例子

 function show(){
    alert("I am global");
 }

 function f() {

    show();

    show = function(){
       alert("I am second");
    }  

    show();   

    function show(){
        alert("I am first");
    }

}
f();
show();

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

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