获取当前函数()范围的所有变量 [英] Get all variables of the current function() scope

查看:81
本文介绍了获取当前函数()范围的所有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题。我想获得当前的函数scrope。我有这个示例代码,我工作正常。

  function nittle(){

var Pen = new Dot(); //通过eval()生成动态
.....
$ b $(窗口中的键){
if(window [key] instanceof Dot){
警报(发现它);
}
}

}

但它似乎不在功能范围内工作。在其外面工作。有没有解决办法?



谢谢。

解决方案

我不知道有任何方法以编程方式确定函数内部声明了哪些变量,除了可能使用 nittle.toString(),然后尝试自己解析它以找到所有变量。 也许这可以为你工作? (但这对我来说太乱了) UPDATE:但是如果变量是通过 eval()创建的,它不会起作用,只需在函数的字符串表示中看到 eval()语句即可。 $ b


是否有解决方法?


您可以在函数中声明单个对象并将所有变量更改为属性

  function nittle(){
var nittleVars = {
var1:something ,
Pen:新的Dot(),
等:whatever
};
$ b $ for(var key in nittleVars){
if(nittleVars [key] instanceof Dot){
alert(found it);







你的更新表明变量是用 eval()创建 - 你仍然可以用对象属性的想法来做到这一点:

  eval(nittleVars.newVar = new Dot()); //在函数


内部

I'm having a problem. I want to get the current function scrope. I have this example code that i'm working ok.

function nittle(){

    var Pen = new Dot(); // Generated dynamical through eval()
    .....

    for(key in window) {
        if( window[key] instanceof Dot ){
            alert("found it");
        }
    }

}

But it seems not to work within the function scope. Work outside of it. Is there a work around ?

Thanks.

解决方案

I'm not aware of any way to determine programmatically what variables have been declared inside a function, except perhaps to use nittle.toString() and then attempting to parse it yourself to find all the variables. Maybe that could work for you? (But it's too messy for me to attempt here.) UPDATE: but if the variables are created via eval() it won't work, you'd just see the eval() statement in the function's string representation.

Is there a work around ?

You could declare a single object in your function and change all the variables into properties of that object:

function nittle() {
  var nittleVars = {
     var1 : "something",
     Pen : new Dot(),
     etc : "whatever"
  };

  for (var key in nittleVars){
    if( nittleVars[key] instanceof Dot ){
        alert("found it");
    }
  }
}

Your update indicates the variables are created with eval() - you could still do that with the object properties idea:

  eval("nittleVars.newVar = new Dot()");  // inside the function

这篇关于获取当前函数()范围的所有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆