在 Javascript 中查找全局变量的最佳方法

Cha*_*ins 0 javascript scope global global-variables

我继承了一个项目,看起来有很多变量污染了全局范围,我想找到所有这些。查找用户引入的全局变量的最佳方法是什么?我想排除默认情况下存在的 window 对象上的属性,只过滤到我们的代码引入的属性。是否有工具或 IDE 插件可以让我轻松识别这些?谢谢

Tho*_*mas 6

将窗口对象中的键与“空”窗口对象的键进行比较:

(function(){
    var iframe = document.createElement('iframe');
    iframe.src = "about:blank";
    document.body.appendChild(iframe);

    var windowVars = Object.keys(iframe.contentWindow);
    var globalVars = Object.keys(window).filter(key => !windowVars.includes(key));

    console.log("global Vars:", globalVars);
    document.body.removeChild(iframe);
})();
Run Code Online (Sandbox Code Playgroud)

现在您必须搜索代码以找到声明它们的行。