如何在javascript中动态访问本地范围?
4 回答
汪汪一只猫
TA贡献1898条经验 获得超8个赞
如何在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]
慕田峪7331174
TA贡献1828条经验 获得超13个赞
要回答你的问题,不,没有办法在没有使用的情况下在本地范围内进行动态变量查找eval()。
最好的选择是让你的“范围”只是一个常规对象[文字](即"{}"),并将你的数据粘贴在那里。
牧羊人nacy
TA贡献1862条经验 获得超7个赞
希望我不会过度简化,但是使用对象这么简单呢?
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- 4 回答
- 0 关注
- 432 浏览
添加回答
举报
0/150
提交
取消
