如何查找函数中定义的变量
假设我有一个很长的 JavaScript 函数,例如
function test() {
var x;
var a;
...
...
...
...
...
}
有什么方法可以让函数本身告诉我到目前为止定义了哪些变量。
function test() {
var x;
var a;
...
...
...
...
... // bit of code that would say to me: x and a.
}
Suppose I have a long javascript function such as
function test() {
var x;
var a;
...
...
...
...
...
}
is there any way I can ask the function itself to tell me what variables were defined so far.
function test() {
var x;
var a;
...
...
...
...
... // bit of code that would say to me: x and a.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不依赖
Function#toString
然后对结果执行字符串处理,这是不推荐的。Function#toString
由大多数浏览器实现,为您提供函数的源代码(带或不带注释,具体取决于),但没有由规范标准化(即使是最新的),我不会不要在生产代码中使用它。No, not without relying on
Function#toString
and then performing string processing on the result, which is not recommend.Function#toString
is implemented by most browsers as giving you the source code of the function (with or without comments, depending), but isn't standardized by the spec (even the latest) and I wouldn't use it in production code.这需要反思。但 Javascript 并没有太多的反射支持。我不认为你能做到这一点,除了这样:解析你自己的函数。
That would require reflection. But Javascript comes without very much any reflection support. I don't think you can do it, except like this: parse your own function.