Calling variables defined in outer function from inner function with debugger

回眸只為那壹抹淺笑 提交于 2019-12-25 05:08:14

问题


From the jQuery docs javascript guide:

Because local scope works through functions, any functions defined within another have access to variables defined in the outer function:

function outer() {
    var x = 5;
    var y = 2;
    function inner() {
        console.log( x );
        debugger; // <-- !!!
    }
    inner();
}
outer()

Console triggered with debugger:

> x
5
> y
ReferenceError: y is not defined

Since variables defined in the outer function can be used by the inner function (E.g. x or y), why is the debugger not able to call the y variable?

I suspect people will answer that the debugger only shows variables defined in the most inner/local scope. The reason for this being that otherwise no distinction could be made using the debugger between the inner and outer scope when inspecting a variable using the debugger in the inner function. Additionally, every variable defined in an outer scope which is executed in the inner scope allows the debugger to access it.

But if that is the case, isn't there some way to still call the variable y from the console inside the inner function? (using a notation respectful of scope, e.g. outer.y)

Edit: Debuggers in other languages

Apparently this behavior of a debugger is not limited to javascript. The Python debugger pdb for example behaves similarly:

def outer():
    x = 5
    y = 2
    def inner():
        print x
        import pdb; pdb.set_trace()
    inner()
outer()

(Pdb) x
5
(Pdb) y
*** NameError: 'y' is not defined

回答1:


Presumably this is an optimisation by the JavaScript engine. Since you're not referring to y within the inner function there is no need to hold on to it in the closure. This will allow it to be garbage collected when the outer function returns.

If you add a reference to y (for example console.log(x, y)) you can see the values of both x and y as you would expect.

isn't there some way to still call the variable y from the console inside the inner function?

Apparently not. You could just add a reference to y within inner while debugging (it doesn't have to do anything, any reference will do).



来源:https://stackoverflow.com/questions/19707213/unable-to-access-local-var-in-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!