微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

了解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();

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

原文地址:https://www.jb51.cc/js/159612.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐