所有可能的方法来声明Javascript变量

Bla*_*ble 7 javascript

要创建一个IDE,它将自动完成用户声明的所有变量,但不会忘记其他变量,Math.PI甚至是模块Math,IDE需要能够识别与用户声明的变量相关的所有标识符.假设您已经可以访问程序的AST(抽象符号表),可以使用什么机制来捕获所有这些变量?

我正在使用reflect.js(https://github.com/zaach/reflect.js)来生成AST.

Ben*_*aum 7

我认为这几乎是不可能的

这就是为什么我认为没有执行它几乎是不可能的:

让我们来看看未开发的部分,从易到难.

容易捕捉:

这里错过了功能范围:

(function(x){
    //x is now an object with an a property equal to 3
    // for the scope of that IIFE.
    x;
})({a:3});
Run Code Online (Sandbox Code Playgroud)

这里有一些有趣的脏技巧:

介绍...鼓卷... 块范围!

with({x:3}){
    x;//x is now declared in the scope of that with and is equal to 3.
}


try{ throw 5}catch(x){ 
    x // x is now declared in the scope of the try block and is equal to 5;
}
Run Code Online (Sandbox Code Playgroud)

(人们在阅读:我请求你不要使用这两个代码来实际确定代码:))

不容易:

括号表示法:

var n = "lo";
a["h"+"e"+"l"+n] = "world"; // need to understand that a.hello is a property.
                        // not a part of the ast!
Run Code Online (Sandbox Code Playgroud)

真正困难的部分:

让我们不要忘记调用编译器这些不会出现在AST中:

eval("var x=5"); // declares x as 5, just a string literal and a function call
new Function("window.x = 5")();// or global in node 
Run Code Online (Sandbox Code Playgroud)

在node.js中,这也可以通过vm模块完成.在浏览器中使用document.write或脚本标记注入.

还有什么?当然,他们可以模糊他们想要的一切:

new Function(["w","i","n","dow.x"," = ","5"].join(""))(); // Good luck finding this!
new Function('new Function(["w","i","n","dow.x"," = ","5"].join(""))()')();// Getting dizzy already?
Run Code Online (Sandbox Code Playgroud)

那可以做些什么呢?

  • 更新符号表(只是相关部分)时,在闭合的定时环境中执行一次代码
  • 查看生成的符号表来自执行的内容
  • 热潮,你有自己的符号表.

这不可靠,但它可能会尽可能接近.

我能想到的唯一其他选择,大多数 IDE正在做的是简单地忽略任何不是:

object.property = ... //property definition
var a = ... //scoped
b = ... //global, or error in strict mode
function fn(){ //function declaration
object["property"] //property with a _fixed_ literal in bracket notation.
Run Code Online (Sandbox Code Playgroud)

还有,功能参数.

我见过没有 IDE可以处理除了这些之外的任何东西.由于它们是迄今为止最常见的,我认为计算它们是完全合理的.

  • 哦,我的...这个答案的恐怖是具有传奇色彩的.我永远不会查看Javascript相同. (2认同)