为什么Chrome开发工具说变量没有定义?

时间:2018-04-14 03:01:16

标签: javascript google-chrome google-chrome-devtools

在下面的代码中,当在断点处暂停时,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();

1 个答案:

答案 0 :(得分:2)

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;添加到内部函数,现在调试器就可以使用它了。

相关问题