2012-06-14 7 views
4

Java 스크립트 메소드를 호출 할 때 참조로 원시 변수 (문자열과 같은)를 전달하는 방법은 무엇입니까? C#에서 out 또는 ref 키워드와 동일합니다.자바 스크립트의 실제 매개 변수를 자동으로 업데이트

나는 var str = "this is a string"; 같은 변수 i가 인수 값을

function myFunction(arg){ 
    // automatically have to reflect the change in str when i change the arg value 
    arg = "This is new string"; 
    // Expected value of str is "This is new string" 
} 
+0

가능한 중복 http://stackoverflow.com/questions/373157/how-can-i-pass- a-function-with-parameters-with-parameters –

+0

이것을 확인하십시오 : http://snook.ca/archives/javascript/javascript_pass/ – kol

+1

가능한 복제본 [자바 스크립트로 참조 문자열 전달] (http : // stackoverflow.com/questions/1308624/pass-a-string-by-reference-in-javascript) –

답변

3

원시 유형을 변경하면 STR의 변화를 반영 할 필요가 자동으로 내 기능에 str을 전달하고 있고, 그 문자열/숫자/부울이있다 가치에 의해 전달. 함수, 객체, 배열과 같은 객체는 참조에 의해 "전달"됩니다.

그럼, 당신은 할 수 없습니다 싶어하지만, 다음이 작동합니다 :의

 var myObj = {}; 
     myObj.str = "this is a string"; 
     function myFunction(obj){ 
      // automatically have to reflect the change in str when i change the arg value 
      obj.str = "This is new string"; 
      // Expected value of str is "This is new string" 
     } 
     myFunction(myObj); 
     console.log(myObj.str); 
+1

이것은 대부분 사실이지만 [pedants는 JavaScript가 순수한 값으로 전달된다는 것을 알려줄 것입니다] (http://stackoverflow.com/a/9070366/201952), 객체에 전달 된 * value *는 그 자체가 참조입니다 . 그러나 이것은 혼란스럽고 실용적인 관점에서 보면 기본적으로 객체가 참조로 전달 된 것처럼 보입니다. – josh3736

+0

음, 그래, 그게 내가 실제로하고 싶은 말이다. – Angel

관련 문제