了解Global& Javascript中的本地范围 [英] Understanding Global & Local Scope in Javascript

查看:111
本文介绍了了解Global& Javascript中的本地范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 Stoyan Stefanov的面向对象的JavaScript 学习Javascript

I've been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov

他提供了一个比较全局和本地范围的示例:

He offers an example comparing global and local scope:

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

看看这个例子,我预计第一个警报是'123',第二个警报是'1'。瞧,Stoyan说:

Looking at this example, I expected the first alert to be '123' and the second alert to be '1'. Lo and behold, Stoyan says:


你可能会期望第一个alert()将显示123(
的值全局变量a)和第二个将显示1(本地a)。
情况并非如此。第一个警报将显示未定义。这是
,因为在函数内部,本地范围比
全局范围更重要。因此局部变量用
覆盖任何全局变量同名。在第一个alert()时,a尚未定义
(因此值未定义)但它仍然存在于本地空间中。

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). 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.

我的解释并不清楚,局部变量如何在第一个警报中覆盖全局变量?任何其他/不同的解释将不胜感激。

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.

推荐答案

它不会覆盖全局变量。发生的事情被称为可变吊装。也就是说, var a; 会插入到函数的顶部。

It is not overriding the global variable. What is happening is called "variable hoisting". That is, 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.

这篇关于了解Global& Javascript中的本地范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆