Why does Chrome debugger think closed local variable is undefined?

后端 未结 5 1058
庸人自扰
庸人自扰 2020-11-22 00:48

With this code:

function baz() {
  var x = \"foo\";

  function bar() {
    debugger;
  };
  bar();
}
baz();

I get this unexpected result:<

5条回答
  •  孤城傲影
    2020-11-22 01:26

    I suspect this has to do with variable and function hoisting. JavaScript brings all variable and function declarations to the top of the function they are defined in. More info here: http://jamesallardice.com/explaining-function-and-variable-hoisting-in-javascript/

    I bet that Chrome is calling the break point with the variable unavailable to the scope because there is nothing else in the function. This seems to work:

    function baz() {
      var x = "foo";
    
      function bar() {
        console.log(x); 
        debugger;
      };
      bar();
    }

    As does this:

    function baz() {
      var x = "foo";
    
      function bar() {
        debugger;
        console.log(x);     
      };
      bar();
    }

    Hope this, and / or the link above helps. These are my favorite kind of SO questions, BTW :)

提交回复
热议问题