Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing closure variables in the console

Given this code

function foo()
{
    var x = 1;

    function bar()
    {
        debugger;
        return x + 1;
    }

    return bar();
}

when I open the Google Chrome's console and and foo() gets executed, the console stops at the debugger line. If I type 'x' in the console, I get Uncaught ReferenceError: x is not defined.

If I want to access x in the console, I have two options:

  • Under Source go to Scope, open Closure, make a right click on x and click Store as Global Variable. This will create a global variable temp1 with which I can access x.
  • edit bar to

    function var()
    {
        x;
        debugger;
        return x + 1;
    }
    

I noticed that when you put a debugger and the code accessed a scope variable at some point, then I can access it in the console.

I found other threads like this one more or less aksing the same question. Is there a better way to access the closure variables?

Btw I use Version 59.0.3071.104 (Official Build) (64-bit) for Debian 8.

like image 898
Pablo Avatar asked Jun 19 '17 15:06

Pablo


Video Answer


1 Answers

I believe you already got the answer in the other thread you referred to. @OwnageIsMagic said it was because of V8 optimization. If you click the function name in the Call Stack, that variable will be accessible then.

like image 147
Marshal Avatar answered Nov 01 '22 17:11

Marshal