bokan bokan - 1 year ago 106
Javascript Question

How to get pointer to a local variable in Javascript?

Let say I know that a variable is called "myVar", it is declared in a self calling function

(function (){
var myVar=0;
}, 3000);

But I don't know where this function is called, and don't want to reverse engineer tons of JS. I want to find a reference to this variable so I can display it in console something like window.rootObject.subObject.myVar . I tried to make a function that does recursive seek for key from the window object, but it does a stackoverflow, certainly because of circular references (an object contain reference to its containing object).

Is there any simple way to find where is this object ?

Answer Source

myVar in your updated example doesn't "belong" to any object you can get a reference to. In specification terms, it belongs to the EnvironmentRecord for the variable environment of the execution context for the call to the anonymous function, but there's no way for you to get a direct access to that object (which may or may not literally exist at runtime at all, depending on how the JavaScript engine being used is implemented).

You seem to believe that all objects (even specification-only objects like environment records) are in a tree and are acessible following a path of references from some root object and so are "discoverable" somehow in code. That's understandable, but it's not the case. Certainly the JavaScript engine has trees like that for garbage collection purposes (for objects that actually get created at runtime), but no, there's no root from which everything can be discovered that you can access in code.