为了账号安全,请及时绑定邮箱和手机立即绑定

如何在javascript中动态访问本地范围?

如何在javascript中动态访问本地范围?

大话西游666 2019-08-13 17:28:57
如何在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()

最好的选择是让你的“范围”只是一个常规对象[文字](即"{}"),并将你的数据粘贴在那里。


查看完整回答
反对 回复 2019-08-13
?
弑天下

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


查看完整回答
反对 回复 2019-08-13
  • 3 回答
  • 0 关注
  • 469 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号