我有问题。我想获取当前的函数范围。我有这个示例代码,我工作正常。
function nittle(){
var Pen = new Dot(); // Generated dynamical through eval()
.....
for(key in window) {
if( window[key] instanceof Dot ){
alert("found it");
}
}
}
但在函数作用域内似乎不起作用。在它之外工作。有解决办法吗?
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.
有解决办法吗?
您可以在函数中声明一个对象,并将所有变量更改为该对象的属性:
function nittle() {
var nittleVars = {
var1 : "something",
Pen : new Dot(),
etc : "whatever"
};
for (var key in nittleVars){
if( nittleVars[key] instanceof Dot ){
alert("found it");
}
}
}
您的更新表明变量是用以下命令创建的eval()
- 你仍然可以使用对象属性的想法来做到这一点:
eval("nittleVars.newVar = new Dot()"); // inside the function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)