-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>