유효범위
불가피하게 전역변수를 사용해야 하는 경우는 하나의 객체를 전역변수로 만들고 객체의 속성으로 변수를 관리하는 방법을 사용한다.
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());
전역변수를 사용하고 싶지 않으면 익명함수를 호출함으로써 이러한 목적을 달성할 수 있다.
(function(){
var MYAPP = {};
MYAPP.calculator = {
'left' : null;
'right' : null;
}
MYAPP.coordinate = {
'left' : null;
'right' : null;
}
function sum(){
return MYAPP.calculator.left + MYAPP.calculator.right;
}
document.write(sum());
}())
자바스크립트는 함수가 선언된 시점에서의 유효범위를 갖는다.
이러한 유효범위의 방식을 정적 유효범위(static scoping), 혹은 렉시컬(lexical scoping)이라고 한다.
var i = 5;
function a(){
var i = 10;
b();
}
function b(){
document.write(i);
}
a();
실행 결과는 5이다.
출처 : https://opentutorials.org/course/743/6495