如何查找函数中定义的变量

发布于 2024-08-14 09:17:35 字数 328 浏览 2 评论 0原文

假设我有一个很长的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰つ倒转 2024-08-21 09:17:35

不,不依赖 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.

荒芜了季节 2024-08-21 09:17:35

这需要反思。但 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文