简体   繁体   English

获取Javascript中的闭包变量列表

[英]Get list of closure variables in Javascript

Are there any ability to get closure variables list (Ok, maybe all scope variables) in JavaScript?是否有任何能力在 JavaScript 中获取闭包变量列表(好吧,也许是所有范围变量)?

Sample:样本:

function factory(){
    var _secret = "Some secret";
    return function(code){
        // How to get parent function variables names here? 
        // ...
    }
}

var inside = factory();

inside();

Assuming this is for debugging purposes, you can try parsing the function body and evaluating identifiers found:假设这是出于调试目的,您可以尝试解析函数体并评估找到的标识符:

 function getvars(fn, _eval) { var words = String(fn).replace(/".*?"|'.*?'/g, '').match(/\\b[_A-Za-z]\\w*/g), ret = {} words.forEach(function(w) { try { ret[w] = _eval(w) } catch (e) {}; }); return ret; } function factory() { var _secret = "Some secret"; var _other = "Other secret"; return function(code){ var vars = getvars(factory, _ => eval(_)); return vars; } } vars = factory()(); document.write('<pre>'+JSON.stringify(vars,0,3));

Needless to say, this is an extremely naive way to deal with code, so handle it with care.不用说,这是一种非常幼稚的处理代码的方式,所以要小心处理。

There's no comprehensive way to get a list of all variables in scope.没有全面的方法来获取范围内所有变量的列表。 You could enumerate over the this object, but that will still only give you a list of the enumerable objects on this , and even at that there will still be things like function arguments that aren't on this .您可以枚举this对象,但这仍然只会为您提供this可枚举对象的列表,即使如此,仍然会有诸如函数参数之类的东西不在this

So no, this cannot be done.所以不,这是不可能的。 Also check out this similar question .也看看这个类似的问题

No, it isn't possible.不,这是不可能的。 ECMAScript specification doesn't expose Enviroment Record objects to end user anywhere. ECMAScript 规范不会在任何地方向最终用户公开环境记录对象。

One way to see them is using console.dir to get all the scopes including closures scopes and their variables list.查看它们的一种方法是使用console.dir获取所有范围,包括闭包范围及其变量列表。 Example:例子:

function factory(){
    var _secret = "Some secret";
    var i = 0;
    return function(){
        i++;    
        return _secret + i;
    }
}

var inside = factory();
inside(); // "Some secret1"
inside(); // "Some secret2"
console.dir(inside); // It shows you all variables in [[Scopes]] > Closure

Image of how you would see the console:您将如何看到控制台的图像:

console.dir 输出

It works in Chromium based browsers.它适用于基于 Chromium 的浏览器。

Edit: Related answer with nested scopes in related question https://stackoverflow.com/a/66896639/2391782编辑:相关问题中嵌套范围的相关答案https://stackoverflow.com/a/66896639/2391782

Since the primary concept of a closure is scope, and vars inside a closure are private, there can be no way to achieve this without exposing them somehow, like via a method.由于闭包的主要概念是作用域,并且闭包内的变量是私有的,因此如果不以某种方式(例如通过方法)公开它们,就无法实现这一点。

What are you really trying to achieve?你真正想要达到什么目标?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM