2014-01-31 1 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

측면이 .. 평가가 높은 방법 평가 '에 대한 보안 – user1428716

+5

의 이유 (jsonPath + "= attrVal")에 대한 JS에 낙담 아이오와되지 같이,'? –

+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