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

All possible ways to declare Javascript variables

本文关键字:有可能 方法 Javascript 变量 声明      更新时间:2023-09-26

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

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

我认为这几乎是不可能的

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

让我们从简单到困难地浏览尚未探索的部分。

易于捕捉:

此处缺少功能范围

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

以下是一些有趣的肮脏把戏

介绍。。。卷筒块范围界定

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;
}

(人们阅读:我恳求你不要在代码中使用最后两个来进行实际作用域:)

不容易:

括号符号:

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

真正困难的部分:

我们不要忘记调用编译器这些不会显示在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 

在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?

那么我们能做些什么呢

  • 当您更新符号表(仅相关部分)时,在一个封闭的定时环境中执行一次代码
  • 查看执行过程中生成的符号表是什么
  • 轰,你给自己弄了一张符号表

这是不可靠的,但它可能是接近你得到的。

我唯一能想到的另一种选择,也就是大多数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.

还有函数参数。

我见过没有IDE能够处理任何,但这些。由于它们是迄今为止最常见的,我认为计算这些是完全合理的。

通过将它们添加到已经存在的对象上。。。。即

window.mynewvar=5;

function mynewfunc() {
}