了解Javascript中的全局和局部范围

我一直在使用 Object-Oriented JavaScript by Stoyan Stefanov学习Javascript

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

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

看看这个例子,我预计第一个警报为’123′,第二个警报为’1′.瞧,斯托扬说:

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.

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

解决方法

它不会覆盖全局变量.发生的事情被称为“可变吊装”.即,变量a;插入函数的顶部.

脚本引擎将您的脚本更改为以下内容

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

需要学习的经验:在使用之前始终声明变量.有些人会说在函数顶部声明所有变量.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...