JavaScript Scope

김서하·2021년 4월 7일
0

JavaScript

목록 보기
5/11
<범위> - 프로그램의 다른 부분에서 일부 변수에 엑세스할 수
        없는 프로그래밍 아이디어.
<블록> - 중괄호 안에 있는 구문 {}
const city = 'New York City';

const logCitySkyline = () => {
 let skyscraper = 'Empire State Building';
 return 'The stars over the ' + skyscraper + ' in ' + city;
};
console.log(logCitySkyline());

<전역 범위> - 프로그램의 모든 부분에서 변수에 엑세스할 수 있는
            컨텍스트(전역 변수 존재)
const color = 'blue';
 
const returnSkyColor = () => {
  return color; // blue 
};
 
console.log(returnSkyColor()); // blue
다른 예
const satellite = 'The Moon';
const galaxy = 'The Milky Way';
const stars = 'North Star';

const callMyNightSky = () => {
	return 'Night Sky: ' + satellite + ', ' + stars + ', and ' + galaxy;
};

console.log(callMyNightSky());

<블록 범위> - 정의된 블록 내에서만 엑세스할 수 있는 변수가 있는
            컨텍스트(지역 변수 존재)
const logSkyColor = () => {
  let color = 'blue'; 
  console.log(color); // blue 
};
 
logSkyColor(); // blue 
console.log(color); // ReferenceError
다른 예
const logVisibleLightWaves = () => {
const lightWaves = 'Moonlight';
 console.log(lightWaves);
};
logVisibleLightWaves(); // Moonlight
console.log(lightWaves); // ReferenceError

<범위 오염> - 전역 범위에서 변수 정의xx!
 너무 많은 전역 변수 존재하거나 다른 범위에서 변수 재사용할 때
let num = 50;
 
const logNum = () => {
  num = 100; // Take note of this line of code
  console.log(num);
};
 
logNum(); // Prints 100
console.log(num); // Prints 100
다른 예
const satellite = 'The Moon';
const galaxy = 'The Milky Way';
let stars = 'North Star';

const callMyNightSky = () => {
  stars = 'Sirius'; // 변수가 할당되어서
	return 'Night Sky: ' + satellite + ', ' + stars + ', ' + galaxy;
};

console.log(callMyNightSky());
console.log(stars()); // 에러

<좋은 범위 지정의 >
 const logSkyColor = () => {
  const dusk = true;
  let color = 'blue'; 
  if (dusk) {
    let color = 'pink';
    console.log(color); // pink
  }
  console.log(color); // blue 
};
 
console.log(color); // ReferenceError
                       동일한 변수이름이 재사용되어서 다른 예
const logVisibleLightWaves = () => {
  let lightWaves = 'Moonlight';
	let region = 'The Arctic';
  if(region === 'The Arctic'){
    let lightWaves = 'Northern Lights';
    console.log(lightWaves());
  };
  
  console.log(lightWaves);
};

logVisibleLightWaves();
profile
개발자 지망생 서하입니당

0개의 댓글