엄지월드

유효범위 본문

Front

유효범위

킨글 2017. 7. 15. 11:10
반응형

불가피하게 전역변수를 사용해야 하는 경우는 하나의 객체를 전역변수로 만들고 객체의 속성으로 변수를 관리하는 방법을 사용한다.


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




'Front' 카테고리의 다른 글

jQuery 자동완성 기능(autoComplete)  (0) 2017.08.22
파일 유효성 체크하는 방법  (0) 2017.07.20
값으로서의 함수  (0) 2017.07.15
js 정규식  (0) 2017.07.15
js  (0) 2017.07.15
Comments