Get all variables of the current function() scope

醉酒当歌 提交于 2019-12-23 18:54:30

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/16633958/get-all-variables-of-the-current-function-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!