2017-04-25 3 views
0

내가 다음 코드 실행에서 이상한 결과를 경험하고이 코드를 실행자체 호출 익명 함수 바로 위에 배치 될 때 함수가 변수에 할당되는 이유는 무엇입니까?

var saySomethingElse, v; 

// This function will not run when the nameless function runs, even if v and saySomethingElse are commented out. 
function saySomething() { 

    alert("something"); 

} 

// When v is uncommented, this function will run when the nameless function below runs.. 
saySomethingElse = function() { 

    alert("something else"); 

} 

//v = "by uncommenting me, saySomethingElse will no longer be called."; 

(function() { 

    if (v) { 

    alert("Now things are working normally.") 

    } 

    alert("This alert doesn't happen if v is commented out."); 

})(); 

를, 하단에있는 익명 함수는 대신 자신 만의 콘텐츠의 saySomethingElse를 호출하지만 v가 주석 처리되지 않으면 예상대로, 모든 작동 : saySomethingElse이 실행되지 않고 익명 함수가 자체 콘텐트를 실행합니다. 나는 이것이 정상적인 행동 일 것이라고 기대하지만, 나는 설명을 찾고있다. 왜 이런 일이 일어나는 지 아는 사람이 있습니까?

체크 아웃 바이올린 : working example 당신은 당신의 익명 함수 saySomethingElse

당신은 항상 제대로 세미콜론으로 익명 함수를 종료한다 끝에 세미콜론을 추가해야

+0

콘솔을 사용하는 방법을 배우는 것이 좋습니다 –

답변

1

. 세미콜론을 사용하여 정상적인 비 익명의 function fooBar() {} 기능을 종료 할 필요가 없습니다.

var saySomethingElse, v; 
 

 
// This function will not run when the nameless function runs, even if v and saySomethingElse are commented out. 
 
function saySomething() { 
 

 
    alert("something"); 
 

 
} // <-- Semi-colon not necessary. 
 

 
// When v is uncommented, this function will run when the nameless function below runs.. 
 
saySomethingElse = function() { 
 

 
    alert("something else"); 
 

 
}; // <-- Semi-colon recommended to prevent errors like you're getting. 
 

 
//v = "by uncommenting me, saySomethingElse will no longer be called."; 
 

 
(function() { 
 

 
    if (v) { 
 

 
    alert("Now things are working normally.") 
 

 
    } 
 

 
    alert("This alert doesn't happen if v is commented out."); 
 

 
})();

당신이 지금 saySomethingElse 제대로 말에 종료 된 것을 기대하는 것처럼 이제 코드 기능.

JavaScript에서는 모든 문장의 끝에 세미콜론을 사용해야하기 때문입니다. 익명 함수 정의는 다른 변수 정의와 마찬가지로 명령문입니다.

+0

화를내는 것입니다. 나는 그 시간을 모두 놓친 세미콜론을 보냈다. 그래도 신속한 대응에 감사드립니다. – Frank