Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically inspect the JavaScript scope chain?

In a JavaScript debugger, I can manually inspect the scope chain of a function. For instance, when executing foo() on this piece of code:

var x1 = "global";
var foo = (function main () {
    var x2 = "inside obj";
    return function internalFoo () {
        var x3 = "inside internalFoo";
        console.log (x1+','+x2+','+x3); // get the scopes
    };
})();
foo ();

and setting a breakpoint on the console.log, I see the following scopes:

Scope Variables seen in Chrome Debugger

Is there some means to do this programmatically?
How can I inspect what is defined at every scope level?

like image 730
Pierre Arnaud Avatar asked Feb 19 '15 07:02

Pierre Arnaud


People also ask

What is scope chain in JavaScript?

Scope Chain means that one variable has a scope (it may be global or local/function or block scope) is used by another variable or function having another scope (may be global or local/function or block scope). This complete chain formation goes on and stops when the user wishes to stop it according to the requirement.

How do you use scope in JavaScript?

In JavaScript, scopes are created by code blocks, functions, modules. While const and let variables are scoped by code blocks, functions or modules, var variables are scoped only by functions or modules. Scopes can be nested. Inside an inner scope you can access the variables of an outer scope.

Can you select the three types of scopes within JavaScript?

JavaScript has 3 types of scope: Block scope. Function scope. Global scope.

What are the two types of scope JavaScript uses?

JavaScript has global scope and local scope. Variables declared and initialized outside any function become global variables. Variables declared and initialized inside function becomes local variables to that function. Variables declared without var keyword inside any function becomes global variables automatically.


1 Answers

I am (pretty) sure this is not possible.
Not even the Chrome-debugger keeps track of your scope all the time, but only when it hits a breakpoint. Keeping track of the scope chain for all the time would cost way too much memory (depending on the complexity of your closures and contexts). See this feature request for further information: https://groups.google.com/forum/#!topic/google-chrome-developer-tools/wKEMpKjXR7s

ECMA 262 (10.3.1) describes how Identifier Resolution has to be done, the most important part of this is to call GetIdentifierReference (lex, name, strict) which is described in ECMA 262 (10.2.1). As far as I know there is no command in any implementation of ECMAScript to call this function at runtime.

However this question (or to be precise it's answer) might be interesting as it comes at least closer to what you asked for.

like image 137
Tim Hallyburton Avatar answered Jan 18 '23 02:01

Tim Hallyburton