2014-01-31 19 views
3

我有一個包裝函數,我使用變量dataObject。我有一個動作來觸發包裝函數中的一些外部函數。eval()工作和分配差異

function wrapper() { 
    var dataObject; 
    var jsonPath = "dataObject[0]['Set1'][0]['Attribute1']"; 
    eval('outsideFunction(dataObject, jsonPath)'); 
} 


function outsideFunction(dataObject, jsonPath) { 
    dataObject[0]['Set1'][0]['Attribute1'] = 'asde'; //This sets the value to dataObject in the wapper 
    var attrVal = '123'; 
    eval("jsonPath = attrVal"); //This doesn't set value to dataObject in the wrapper but in the local dataObject 
} 

爲什麼使用eval直接分配和分配的動作有所不同?

+0

作爲一個側面不..評估和演示IA高度在JS氣餒如何約'EVAL安全 – user1428716

+5

原因(jsonPath + 「= attrVal」);'? –

+1

^^^^在你的代碼中,你正在評估的是表達式''dataObject [0] ['Set1'] [0] ['Attribute1']「='123'',即你正在給字符串賦值另一個字符串值,這是不可能的。但是,如果將jsonPath與另一個字符串連接起來,則結果爲表達式'dataObject [0] ['Set1'] [0] ['Attribute1'] ='123''。但是,請注意,這是非常可怕的代碼。看看這個問題,而不是:http://stackoverflow.com/q/13719593/218196 –

回答

1

根據你的data[0]['Set1'][0]['Attribute1']的結構,可以寫成data[0].Set1[0].Attribute1,這裏是代碼,但我想你不太清楚你要求的套數。

var wrapper, outsideFunction; 

wrapper = function(){ 

    someOb = {}; 

    var data = [ 
    { 
     Set1: [ 
     { 
      Attribute1: null, // we will change null to 'asdf' below 
     }, 
     ], 
    }, 
    ]; 

    outsideFunction(data, someOb); 

    console.log(someOb.newProp, someOb.dumb); 
    // outputs 'hehehehe', undefined 

}; 

outsideFunction = function(data, blah) { 

    data[0].Set1[0].Attribute1 = 'asdf'; 

    //blah is a reference to someOb 
    // we can change a part of blah and it will look at the reference and change someOb 
    blah.newProp = 'hehehehe'; 

    // but if we do `blah =`, then we reference a new object 
    // This won't affect someOb, blah will just be a different object talking about something else 
    blah = { dumb: false }; 

}; 

所以,就像我說的,你的數據對象是編號集,(你有[0]),然後命名集(Set1),然後編號集([0]),我不認爲你意味着要嵌套這麼多。

numberedSet = [ 
    { 
    name: 'dan', 
    likes: [ 
     'coding', 'girls', 'food', 
    ], 
    }, 
    { 
    name: 'Sreekesh', 
    }, 
] 

namedSet = { 

    dan: { 
    isPerson: true, 
    likes: [ 
     'coding', 'girls', 'food', 
    ], 
    }, 

    Sreekesh: { 
    isPerson: true, 
    askedQuestion: function(){ 
     return true; 
    }, 
    } 

}; 

numberedSet[0].name == dan; // true 
numberedSet[0].likes[1] == 'girls'; // true 
namedSet.dan.isPerson == true; // true 
namedSet.Sreekesh.askedQuestion(); // true