Hoisting, TDZ

ou·2024년 1월 19일
0

basic

목록 보기
9/24

Hoisting(호이스팅)

함수 내부의 선언들을 최상단으로 끌어올려 선언하는 것
선언과 초기화가 동시에 이루어지는 경우(var, 함수선언문)도 있음

var, 함수선언문

호이스팅되며 선언, 초기화 동시에 이루어짐

console.log('a', a); // undefined;
var a = 'a';
b();
var c = 'c';
console.log('c', c) // c
function b(){
	console.log('c', c); // undefined;
}
위 코드를 호이스팅이 적용됐다치고 다시 써보면 아래와 같다
-------------------------------------------
var a; //선언, 초기화
var c; //선언, 초기화
function b(){
	console.log('c', c); //선언, 초기화, 할당
}
//여기까지 호이스팅
console.log('a',a)
a = 'a';
b();
c= 'c';
console.log('c', c)

흠.. 함수선언문은 할당까지 같이 이루어지는게 또 달라서 이해가 잘안된다. 관련해서 검색해봤는데 별로 내용이 없다. 추가로 알게되면 와서 수정할 것.

let, const, 함수표현식

호이스팅되지만 TDZ에 포함됨
에러 메세지를 보면 before initialization 이다.
즉 초기화 전에 접근할 수 없다는 것.
내부적으로 선언은 됐으나 초기화는 되지 않은 것으로 보인다.

//원래는 is not defined 오류가 나면 더 이상 진행되지 않겠지만 여기서는 코드가 계속 진행된다고 가정
console.log(a); // Cannot access 'a' before initialization
console.log(b); // Cannot access 'b' before initialization
console.log(c); // Cannot access 'c' before initialization
let a = 'a'
const b = 'b'
const c = ()=>{
	console.log(b); //b
    console.log(d); //Cannot access 'd' before initialization
}
c();

const d = 'd';

호이스팅되지만 TDZ에 포함되기 때문에 error 뿜뿜

TDZ(Temporal Dead Zone)

JavaScript에서 변수가 선언되었지만 초기화되기 전의 일시적인 상태

보통 let, const, 함수표현식 정도만 나오는데 class, super 등 더 있다. 흔히 나오는 let, const, 함수표현식은 제외하고 작성하겠다

class

new Car() // Uncaught ReferenceError: Cannot access 'Car' before initialization

class Car {
	constructor(){
    	this.name = "car";
    }
}

constructor() 내부의 super()

부모 클래스 상속을 받았다면 constructor 내 this는 super 호출 전 TDZ에 있음

class Car {
	constructor(brand){
    	this.brand = brand;
    }
}

class Hyundai extends Car {
	constructor(model){
    	this.model = model;
    	super("hyundai");
    }
}

new Hyundai(); // Must call super constructor in derived class before accessing 'this' or returning from derived constructor
//대충 this보다 super를 먼저 호출하라는 말

참고자료
https://ui.toast.com/weekly-pick/ko_20191014 (⭐⭐⭐)
https://yoosioff.oopy.io/0e9733bb-1258-456f-9664-7d0425c43401 (호이스팅이 발생하는 이유 ⭐)
https://80000coding.oopy.io/e1721710-536f-43f2-823b-663389f5fbfa
https://velog.io/@bathingape/JavaScript-var-let-const-%EC%B0%A8%EC%9D%B4%EC%A0%90
https://velog.io/@juunghunz/let-var-const%EC%9D%98-%EC%B0%A8%EC%9D%B4%EC%A0%90%EA%B3%BC-%ED%98%B8%EC%9D%B4%EC%8A%A4%ED%8C%85-Hoisting
https://medium.com/hcleedev/web-hoisting-%ED%98%B8%EC%9D%B4%EC%8A%A4%ED%8C%85%EC%9D%B4%EB%9E%80-javascript-6cec99aa19b4 (⭐⭐)

profile
경험을 현명하게 사용한다면, 어떤 일도 시간 낭비는 아니다.

0개의 댓글

관련 채용 정보