Hoisting

송승찬·2020년 9월 6일
0

TIL

목록 보기
19/52
post-thumbnail

호이스팅?

개념

  • 변수 선언/함수 선언을 유효 scope의 가장 위로 끌어올리는 것을 의미한다.

특징

  • var로 선언된 변수/함수 선언식만 끌어올린다(let,const,함수 표현식은 끌어올리지X / 할당된 값도 끌어올리지X)
  • 실제 메모리에는 변화X / 실제 코드가 끌어올려지는 건 아니고,parser내부에서 끌어 올려 처리하는 것

동작 방식

  • JS parser가 함수 실행 전, 함수 scope안에 선언된 것들을 훑어본 후, 변수/함수선언에 대한 정보를 기억하고 있다가 실행시킨다

변수 호이스팅

console.log('Hoisting');
var name='Korea'; //var
let name2 ='Seoul'; //let
호이스팅된 결과:
var name; // 선언된 것만 끌어올려짐
console.log('Hoisting');
name = 'Korea'; // 할당된 값은 제자리에 존재
let name2='Seoul'; // let,const선언은 끌어올리지X

함수 호이스팅

  foo();
  foo2();

  function foo() { // 함수선언문
          console.log("1");
  }
  var foo2 = function() { // 함수표현식
          console.log("2");
  }
  • 호이스팅된 결과
var foo2; 선언된 것,현재는 undefined
function foo () { 함수 선언은 끌어올린다.
	console.log("1");
}
foo();
foo2(); => TypeError: foo2 is not a function
foo2 = function() { 할당된 것은 끌어올리지X
          console.log("2");
  }

함수 선언식/표현식에서 호이스팅

선언된 순서에 따라 잘 실행되는 경우
function seoul(name) { =>함수 선언식
  var inner = function () { => 함수 표현식
    return name;
  };
  var result = inner(); => 'Seoul Lite;
  console.log(`Name is ${result}`);
}
seoul("Seoul Lite"); =>Name is Seoul Lite

호이스팅이 일어나나, 에러 발생하는 경우
function seoul2(name) {
  console.log(inner); =>undefined; 선언은 됬지만 값이 할당이 아직 안되었기에
  var result = inner(); => Error; inner는 undefined라 함수 아니기에 실행불가
  console.log("name is " + result);
  
  var inner = function () {
    return name;
  };
}
seoul2("Seoul Lite"); => TypeError: inner is not a function(inner실행시 undefined여서)
  • 위에 것을 JS Parser 통한 호이스팅한 결과
function seoul2 (name) {
  var result;
  var inner; 
  Hoisting - 선언된 것만 스코프의 가장 위로 끌어옴,아직 값이 할당되지는X
 
  console.log(inner); =>undefined
  result = inner(); => inner is not function
  console.log('name is'+result);

  inner = function () {
    return name;
  }
}
seoul2("Seoul Lite"); => TypeError: inner is not a function(inner실행시 undefined여서)

출처:https://gmlwjd9405.github.io/2019/04/22/javascript-hoisting.html

profile
superfly

0개의 댓글