简体   繁体   中英

How to access javascript variable stored in function closure from browser console?

Lets say I have a global function:

function Init()
{
       var v = 10;
       window.GlobalFunction = function()
       {
          // Global Function has access to v, because of closure
          alert(v);
       }
}

Init();

How I can get value of v from FireBug console? I can put break point there and see value. However this is not enough for me. I want to build FireFox addon for third party website, so I need access this variable, but can't change source code.

If v is a global variable like you say, then you should just be able to type v at the console to get its value.

If v is not a global, then you can only access it from within the function that contains it. JavaScript is a function-scope language, and the var keyword indicates that the variable is accessible only within the current scope. If you don't want to use a breakpoint/debugger, if you can't modify the source, and if the source has no getter method for the variable, you may be out of luck.

Trying to get creative here, you might be able to create an object based on the prototype of Init or whatever object contains it (using, for example, the new keyword) and add a getter function to your version of the object. Then use your new object wherever you were previously using the original code's object.

If you mean how can you access the variables capture by closure from outside the function that captured it, you can't. The console does not give you any special access to the state, it executes JavaScript as if you were executing eval() at the current break-point (or globally if you are not at a break-point). If you cannot access the variable from JavaScript you cannot access it from the console either.

As you noted, you can only access v when it is in scope, that is when you are stopped at a break-point that and v is in scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM