亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在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 關注
  • 490 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號