Getting All Variables In Scope

前端 未结 10 2145
小蘑菇
小蘑菇 2020-11-22 09:10

Is there a way to get all variables that are currently in scope in javascript?

10条回答
  •  粉色の甜心
    2020-11-22 09:46

    I made a fiddle implementing (essentially) above ideas outlined by iman. Here is how it looks when you mouse over the second ipsum in return ipsum*ipsum - ...

    The variables which are in scope are highlighted where they are declared (with different colors for different scopes). The lorem with red border is a shadowed variable (not in scope, but be in scope if the other lorem further down the tree wouldn't be there.)

    I'm using esprima library to parse the JavaScript, and estraverse, escodegen, escope (utility libraries on top of esprima.) The 'heavy lifting' is done all by those libraries (the most complex being esprima itself, of course.)

    How it works

    ast = esprima.parse(sourceString, {range: true, sourceType: 'script'});
    

    makes the abstract syntax tree. Then,

    analysis = escope.analyze(ast);
    

    generates a complex data structure encapsulating information about all the scopes in the program. The rest is gathering together the information encoded in that analysis object (and the abstract syntax tree itself), and making an interactive coloring scheme out of it.

    So the correct answer is actually not "no", but "yes, but". The "but" being a big one: you basically have to rewrite significant parts of the chrome browser (and it's devtools) in JavaScript. JavaScript is a Turing complete language, so of course that is possible, in principle. What is impossible is doing the whole thing without using the entirety of your source code (as a string) and then doing highly complex stuff with that.

提交回复
热议问题