알다시피 변수는 함수에서 실제로 선언 될 수 있습니다. 그러나 함수를 사용하기 전에 선언해야합니다. 즉 함수가 호출되기 전에 선언되어야합니다.
나는 무엇을 의미 하는지를 보여주기 위해 테스트 시나리오를 만들었습니다. 나는 (파일 : //$path_to_file/test.html를) 내 Firefox4에서이 텍스트 파일을로드하면
<script type="text/javascript">
var a = "hello"; // <- the declaration of the variable before the function
function b(){ // <- the actual function
a += " world";
alert(a);
}
b(); // <- and here it is called
</script>
: 내가 경고 상자를 얻을 수
나는 다음과 같은 간단한 내용으로
test.html
라는 TEXTFILE을 생성 메시지는
Hello world
입니다.
<script type="text/javascript">
function b(){ // <- the actual function
a += " world";
alert(a);
}
var a = "hello"; // <- the declaration of the variable under the function
b(); // <- and here it is called
</script>
결과는 동일 :
는 그럼 난 순서 변경
Hello World
을하지만이 같은 통화에서 선언 퍼팅 때 :
<script type="text/javascript">
function b(){ // <- the actual function
a += " world";
alert(a);
}
b(); // <- and here it is called
var a = "hello"; // <- the declaration of the variable under the call
</script>
나는 다른 결과를 얻었다 :
undefined world
. JavaScript는
a
이 무엇인지 모르기 때문에
undefined
으로 처리합니다.
는 물론 숫자의 합은 문자열의 합에서 다르게 해석 될 수 있었다, 그래서 나는이 테스트 :
<script type="text/javascript">
function b(){ // <- the actual function
a += 3;
alert(a);
}
b(); // <- and here it is called
var a = "hello"; // <- the declaration of the variable under the call
</script>
결과가 있었다 : NaN
이 Not a Number
을 의미한다.
JS의 게으름과 관용에 관한 이야기입니다. 물론 변수와 함수의 범위와 관련하여 질문을 해석 할 수도 있습니다. 하지만 거기에는 이미 2 가지 대답이 있습니다. 물론, 그들이 충분하지 않다면 나는 또한 여기서 상세한 설명을 편집 할 수있다.
대단히 감사합니다. 도와 주셔서 정말 고맙습니다. 다시 한 번 감사드립니다. – Muzammil