奇怪的可变范围问题

Strange variable scope issue

本文关键字:范围 问题      更新时间:2023-09-26

我不太确定为什么会发生这种情况,如果有人能向我解释这一点,那就太好了。

所以我得到了以下代码:

var text = 'yes';
(function f() {
    alert(text);
})();

它按预期提醒"是"。但是如果我像这样扩展它:

var text = 'yes';
(function f() {
    alert(text);
    var text = 'no';
})();

我几乎希望这也会提醒"是",然后覆盖本地范围内的文本变量。但相反,它会发出未定义的警报。

在当前的Chrome和Firefox中进行了测试,所以这似乎是一种通缉行为?!

变量(和函数)声明被提升到范围的顶部。所以你的代码等效于:

var text = 'yes';
(function f() {
    var text;    // shadows the outer variable; initialised with `undefined` 
    alert(text); // still undefined
    text = 'no'; // now it has the value 'no'
})();

您将其声明为该范围内的新变量,因此它不会覆盖。尝试:

var text = 'yes';
(function f() {
    alert(text);
    text = 'no';
})();

演示