如何在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]
3 回答

蛊毒传说
TA贡献1895条经验 获得超3个赞
要回答你的问题,不,没有办法在没有使用的情况下在本地范围内进行动态变量查找eval()
。
最好的选择是让你的“范围”只是一个常规对象[文字](即"{}"
),并将你的数据粘贴在那里。

弑天下
TA贡献1818条经验 获得超8个赞
希望我不会过度简化,但是使用对象这么简单呢?
var test = { getValue : function(localName){ return this[localName]; }, setValue : function(localName, value){ return this[localName] = value; }};>>> test.a = 123>>> test.getValue('a')123>>> test.a123>>> test.setValue('b', 999)999>>> test.b999
添加回答
举报
0/150
提交
取消