为什么Chrome开发工具会显示变量未定义?

7
在下面的代码中,在断点处暂停时,Chrome开发工具会告诉我"foo"是或否未定义,这取决于console.log行是否被注释掉。
一旦到达断点,如果您在控制台中键入"foo",或者将其添加为观察变量,如果控制台语句已被注释,则会显示foo未定义,但是如果控制台语句未被注释,则会正确显示foo的值(1)。为什么会这样?

function func1(){

    let foo = 1; 

    var func2 = function (){
        function func3 (){
            let foo2 = 4;
            // put breakpoint here
            let foo3 = 5;
            // console.log(foo);  //says foo is undefined when this line commented
        }
        func3();
    }
    func2();
}

func1();


@wOxxOm 是的,那就是问题所在!谢谢! - Dustin
1个回答

5

Chrome调试器对捕获变量非常微妙。

由于您的内部func3没有引用foo,在调试器中,您将无法记录它 - 即使在写了实际代码后,它也可以工作。

尝试这个:

function func1(){

    let foo = 1; 

    var func2 = function (){
        function func3 (){
            let foo2 = 4;
            foo; // Note that I'm just referencing the variable, not doing anything with it
            // put breakpoint here
            let foo3 = 5;
            // console.log(foo);  //says foo is undefined when this line commented
        }
        func3();
    }
    func2();
}

func1();

只需在内部函数中添加foo;,现在调试器将使其对您可用。


你的“回答”暗示了这是一个Chrome特定的问题。“如果我没记错”的话 - 这在所有浏览器中都会发生... - Seth McClaine
根据相关问题中的海报,在Firebox中,调试器的行为符合预期,即使没有真正引用它的代码,变量也对调试器可见。 - Dustin
1
据我所知,这是特定于Chrome调试器的。 - AnilRedshift

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接