Lexcial Scope

송승찬·2020년 9월 9일
0

TIL

목록 보기
23/52

Lexical Scope란?

정의

  • 함수의 상위 scope가 함수 실행이 아닌, 함수 정의할 때를 기준으로 설정되는 것

변수를 함수 안에서 새로 선언할때

let string = 'Seoul';

const foo = () => {
  let string='100000';
  foo2();
}

const foo2 = () => {
  console.log(string); 
}

foo();

const foo = () => { let string='100000'; foo2(); }
변수를 새로 선언,이 string은 foo안에서 scope가짐

const foo2 = () => { console.log(string); }

  • foo2내부에 string 변수가 없으므로, scope체인에 따라 더 상위 scope를 참조

  • 결국 전역변수 string = 'Seoul'을 string의 값으로 참조하고,함수 정의될 때를 기준으로 scope결정하므로 foo2()는 'Seoul'을 출력

  • 따라서 foo(); =>Seoul을 출력

변수 재할당 시

let string2 = 'Seoul';

const foo3 = () => {
  string2를 재할당,scope는 전역변수 string2
  string2='100000';
  foo4();
}

const foo4 = () => {
  console.log(string2); 
}

console.log('Before foo4:',string2) -> 전역변수 string2의 값Seoul가 출력
foo3(); -> foo3()가 string2='100000'으로 재할당->100000을 출력
console.log('After foo4:',string2) ->string2에 재할당 된,100000가 출력
profile
superfly

0개의 댓글