汪汪一只猫
如何在javascript中动态访问本地范围?如果要动态使用全局函数和变量,可以使用:window[functionName](window[varName]);是否可以对本地范围内的变量执行相同的操作?这段代码工作正常,但目前使用eval,我正在考虑如何做到这一点。var test = function(){
//this = window
var a, b, c; //private variables
var prop = function(name, def){
//this = window
eval(name+ ' = ' + (def.toSource() || undefined) + ';');
return function(value){
//this = test object
if ( !value) {
return eval('(' + name + ')');
}
eval(name + ' = value;')
return this;
};
};
return {
a:prop('a', 1),
b:prop('b', 2),
c:prop('c', 3),
d:function(){
//to show that they are accessible via to methods
return [a,b,c];
}
};}();>>>testObject>>>test.propundefined>>>test.afunction()>>>test.a()1 //returns the default>>>test.a(123)Object //returns the object>>>test.a()123 //returns the changed private variable>>>test.d()[123,2,3]