2017-02-25 10 views
1

ES6 기본 매개 변수로 재생 중입니다. 이상한 동작이 있습니다.ES6 기본 매개 변수 : 값이 올바르게 지정되지 않았습니다.

function test(firstValue, secondValue=5){ 
    console.log("firstValue: " + firstValue); 
    console.log("secondValue: " + secondValue); 
    console.log("----------") 
} 

test(2, secondValue = 3) 
test(secondValue = 3) 

그 출력 :

firstValue: 2 
secondValue: 3 
---------- 
firstValue: 3 
secondValue: 5 
---------- 

후자의 경우, I는 firstValue: undefinedsecondValue: 3 예상

여기서 문제의 간단한 예이다. 이 동작은 정상적인 것입니다. 내가 놓친 게 있니?

+1

secondValue = 3은 단지 일반적인 할당입니다. 정말 그냥 테스트 (3) – Joe

+1

@ 조 : [암시 적 글로벌] (http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) *을 만드는 부작용 (내 블로그 게시물)*. –

+4

매개 변수의 기본 이니셜 라이저에는 JavaScript에없는 명명 된 인수가 없습니다. – Bergi

답변

1

선언하지 않고 전역 변수를 사용하고 있습니다. 할당은 전역 변수를 생성하며 함수 test의 변수에는 영향을 미치지 않습니다. 이러한 로컬 변수는 호출 범위와 독립적입니다. 당신은 destructuring을 수행 할

1

function test(firstValue, secondValue=5){ 
 
    console.log("firstValue: " + firstValue); 
 
    console.log("secondValue: " + secondValue); 
 
    console.log("----------") 
 
} 
 

 
var secondValue; // with declaration 
 
console.log(secondValue); 
 
test(2, secondValue = 3) 
 
test(secondValue = 3) 
 
console.log(secondValue);
는 것 같아요 :

function test({firstValue, secondValue = 5} = {}){ 
 
    console.log("firstValue: " + firstValue); 
 
    console.log("secondValue: " + secondValue); 
 
    console.log("----------") 
 
} 
 

 
test() // prints firstValue: undefined, secondValue: 5 
 
test({}) // prints firstValue: undefined, secondValue: 5 
 
test({firstValue: 2}) // prints firstValue: 2, secondValue: 5 
 
test({secondValue: 3}) // prints firstValue: undefined, secondValue: 3

+0

좋은 지적으로서, OP는 명명 된 인수를 찾고있을 수 있습니다 (기본값을 사용하는 방법에 대해 혼동하는 것과 반대). 그렇다면 파괴가 갈 수있는 방법 일 수 있습니다. –

5

당신이

test(2, secondValue = 3) 
,

당신은 사실상,이 일을하고 있습니다 :

secondValue = 3 
test(2, 3) 

첫 번째 부분 (secondValue = 3)는 The Horror of Implicit GlobalssecondValue 감사라는 전역 변수를 생성 * 그것은 당신의 함수에서 secondValue 매개 변수와는 아무 상관이있다.. JavaScript는 명명 된 인수가 없습니다. 예를 들어, 인수 목록의 올바른 위치에 놓는 것 외에는 호출 할 때 "secondValue의 값은 여기에 있습니다"라고 말할 수 없습니다. 호출 할 때 이름을 지정하려면 구조화를 cubbuk points out으로 사용할 수 있습니다 정말 인자라는 것이 아니라, 목적의 동일한 종류를 제공 할 수 있습니다.) 할당의 결과가 할당 된 값 (그래서 secondValue = 3 세트 secondValue을에이기 때문에

test3를 전달하는 두 번째 부분은() 발생하는 3이고 결과는 3이고, 이는 test으로 전달됩니다.

test3으로 전화 하시려면 secondValue으로 전화하십시오. 예 :: 당신이 두 번째 오프를 마칠 경우

test(2, 3); 

은 기본값이 사용됩니다

test(2); 

예 :

function test(firstValue, secondValue=5){ 
 
    console.log("firstValue: " + firstValue); 
 
    console.log("secondValue: " + secondValue); 
 
    console.log("----------"); 
 
} 
 

 
test(2, 3); 
 
test(2);


*(그건 저의 빈혈에 관한 게시물입니다)

+0

감사합니다! 위대한 답변, 자세한 설명, 그리고 내 즐겨 찾기에 추가 할 새로운 블로그 :) 파이썬에서 왔어, 나는 내 마음을 자바 스크립트 개발자로 생각하도록 전환했습니다. 따라서 예상 결과를 얻으려면 객체를 인수로 전달하는 것이 가장 좋습니다. –

+0

@ErickHupin : :-) 원하는 결과가 무엇인지에 따라 다릅니다. 호출 할 때 "인자"라고 이름을 정하고 싶다면'test ({firstValue : 2, secondValue : 3}) '를하고 destructuring을 [cubbuk으로 표시] (http : // stackoverflow)로 사용하십시오. .com/a/42458580/157247) (단, 그 대답에 대한 필자의 메모를 보면 더 간단 할 수 있음). 그러나 기본값을 원할 경우 전화 할 때 이름을 지정하지 않고이 대답과 같이 기본값을 지정하면됩니다. –

+0

@ ErickHupin : (cubbuk이 지금 그의 답변을 업데이트 했으므로 위에서 언급 한 의견을 삭제했습니다.) –