자바스크립트 (javascript) 전역변수와 지역변수

코딩하는감자·2021년 5월 31일

-20210531

<!DOCTYPE html>
<html>

<body>

<script type="text/javascript">
var vscope = 'global';	// 전역변수
function fscope1(){
	var vscope = 'local';	// 지역변수 vscope를 선언하고 값 넣는다.
}
fscope1();	// 지역변수가 선언되고 값이 들어간다
alert(vscope);	// 전역 변수를 바꾸지 않아 global 출력

function fscope2(){
	vscope = 'local';	// 전역변수 vscope 값 변경
}
fscope2();	// 전역변수 값 변경
alert(vscope);	// 전역변수 값 바뀌어 local 출력
</script>

</body>
</html> 

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
	// 전역 변수를 사용하고싶지 않을 때
    (function(){
    	var MYAPP = {}
        MYAPP.calculator = {
        	'left' : null,
            'right' : null
        }
        MYAPP.coordinate = {
        	'left' : null,
            'right' : null
        }
        
        MYAPP.calculator.left = 10;
        MYAPP.calculator.right = 20;
        function sum(){
        	return MYAPP.calculator.left + MYAPP.calculator.right;
        }
        document.write(sum());
    }())
    // 익명함수를 통해서 지역변수로만 사용하게 한다.
</script>
</body>
</html>

출처 : https://velog.io/@jsleeg98/JavaScript-%EC%A0%84%EC%97%AD%EB%B3%80%EC%88%98%EC%99%80-%EC%A7%80%EC%97%AD%EB%B3%80%EC%88%98

profile
나는 말하는 감자다

0개의 댓글