JavaScript의 Scope는 Block(블록 { } ) 이 아닌 Function(함수)에 의해 정해집니다.


우선 scope에 대한 간단한 예시 입니다. 


scope(유효범위) 란 ?


JavaScript 뿐만 아니라 모든 프로그래밍 언어에서도 통용되는 말이며


block Scope라 함은 

{

  변수 선언 

}

시 block 을 나가면 선언된 변수가 block 안에서만 생존 하는 것을 말합니다.

JavaScript는 기본적으로 block Scope가 아니라 Function Scope 입니다.

function a(){

변수 선언! (A)

    {  

     변수 선언 !(B) 

   }



// 변수 A와 B둘다 살아있음

}



이와 같이 변수를 선언해도 펑션안에서는 어떻게든 살아서 있기 때문에 접근도 가능합니다.

기본적인 block Scope는 C 언어를 보면 알수 있습니다.



블록 안에서 선언된 변수 들은 블록 안에서 끝나지 않고 Function(함수) 단위로 가게 됩니다.


그에 해당 하는 테스트 샘플 코드입니다.





function foo()
{
		console.warn('__Before__');	
		typeof first ==='number' ? console.log('first exist') : console.error('first not exist');
		typeof Internal==='function' ? Internal() : console.error('not exist');
		/*
			first not exist  'number'로 비교하였지만 undefined로 호이스팅(끌어올리다) 
			Internal exist   'function' 으로 비교하여 참조 의 호이스팅이 되는점 확인 -> 실제 함수 사용까지 가능)

		*/
		var first = 1;
		function Internal(){console.log("Internal exist");}

		console.warn('__after__');
		typeof first ==='number' ? console.log('first exist') : console.error('first not exist');
		typeof Internal==='function' ? Internal() : console.error('not exist');

		/*
			first exist 
			Internal exist 
		*/
		if(first===1){var third = 3;};

		typeof third==='number' ? console.log('third exist') : console.error('third not exist');
		
		/*
			third exist  var third 선언은 if(first===1) 분기를 타고 블록(block) 안에 선언되었지만 밖에서도 참조가 가능
		*/

}
foo();






Hoisting ?

코드 실행 전의 변수와 함수 선언을 해당 범위의 맨위로 이동 시키는 JavaScript 의 매커니즘 


고려해야 할 조건이 있습니다.


1. 변수 할당은 함수 선언보다 우선 

2. 함수 선언은 변수 선언보다 우선 

-> 하지만 함수 선언이 변수 할당을 넘어 서진 않습니다.



관련 참고 사이트 // 설명이 잘 되어있습니다. 

https://scotch.io/tutorials/understanding-hoisting-in-javascript






이런느낌으로 알고 지나가는게 좋을 것 같습니다.


펑션은 호이스팅으로 참조까지 가능하지만


변수(var)는 undefined로 호이스팅이 되는점









+ Recent posts