[英]node.js capture closure variables
I'm working on a simple debug function that evaluates a closure and gets all the relevant variables names in node.js. 我正在研究一个简单的调试函数,该函数评估闭包并在node.js中获取所有相关的变量名称。 It should work at runtime. 它应该在运行时工作。 So, is there a way to automatically capture all the variable names in a closure? 那么,有没有一种方法可以自动捕获闭包中的所有变量名? For example, is it possible to know the existence of "b", "c" and "d" variables in the following case? 例如,在以下情况下是否可以知道“ b”,“ c”和“ d”变量的存在?
var d=3;
function a(c){
var b = true;
eval( debug(/* need to access in runtime something like ["b","c","d"] */) );
}
function debug(vars){
var txt = "";
for(var i=0; i<vars.length; loop++){
txt+="console.log('"+vars[i]+":' + " vars[i] + ");"
}
return txt
}
I could use brute force to scan a.toString() searching for all the "var " and for all the arguments parameters, but is there a native function to find it or a special variable (something like callee. vars ) to find the variables names in the closure? 我可以使用蛮力扫描a.toString()来搜索所有“ var”和所有arguments参数,但是是否有本地函数可以找到它或使用特殊变量(如callee。vars )来找到变量名称在关闭?
I know "eval" is a big no, but I'm only using that at development environment. 我知道“评估”是一个很大的限制,但我只是在开发环境中使用它。
Yes there is. 就在这里。 Just return a function to close over c
and set another var to that closure. 只需返回一个函数以关闭c
并为该关闭设置另一个var。 Like this. 像这样。
function a(c){ var b = true; return function () { console.log(c); }; } var d = a(false); // undefined d(); // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.