Why does Chrome debugger think closed local variable is undefined?

后端 未结 5 996
庸人自扰
庸人自扰 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:38

    Wow, really interesting!

    As others have mentioned, this seems to be related to scope, but more specifically, related to debugger scope. When injected script is evaluated in the developer tools, it seems to determine a ScopeChain, which results in some quirkiness (since it's bound to the inspector/debugger scope). A variation of what you posted is this:

    (EDIT - actually, you mention this in your original question, yikes, my bad!)

    function foo() {
      var x = "bat";
      var y = "man";
    
      function bar() {
        console.log(x); // logs "bat"
    
        debugger; // Attempting to access "y" throws the following
                  // Uncaught ReferenceError: y is not defined
                  // However, x is available in the scopeChain. Weird!
      }
      bar();
    }
    foo();
    

    For the ambitious and/or curious, scope (heh) out the source to see what's going on:

    https://github.com/WebKit/webkit/tree/master/Source/JavaScriptCore/inspector https://github.com/WebKit/webkit/tree/master/Source/JavaScriptCore/debugger

提交回复
热议问题