Language/JS(Node.js)

[Javascript] 자바스크립트 함수와 클래스의 this binding

Joonfluence 2022. 3. 29.

서론


오늘은 자바스크립트에서의 함수와 클래스의 this binding의 차이점에 대해서 알아보도록 하겠습니다.
차이점을 알기 위해선, this가 동작하는 방식에 관해 이해해야 합니다.

본론

함수에서의 this


함수에서의 this는 실행환경(런타임)과 함수가 선언된 방식에 따라서 다릅니다. 먼저 런타임이 node.js에서 확인해보도록 하겠습니다. 함수 선언식과 함수 표현식으로 선언된 함수 안에서의 this는 global 객체를 가리킵니다. 반면, 화살표 함수로 선언된 this는 module.exports를 가리킵니다. 그 까닭은 후자에선 상위 스코프의 this를 가리키는데, 전역 스코프에서의 this가 가리키는 것이 module.exports 이기 때문입니다.

function printThis() {
    console.log(this);
}

printThis(); // global

const arrowPrintThis = () => {
    console.log(this); 
}

arrowPrintThis();

console.log(this === module.exports); // true

브라우저의 경우에는 또 다릅니다. 함수 선언 방식과 상관 없이, this는 window 객체를 가리킵니다. 전역 스코프에서도 마찬가지입니다.

클래스에서의 this


두 런타임 환경 모두, 객체 메서드 내에서 this는 클래스 객체 자체를 가리킵니다.

function printThis() {
    console.log(this);
}

printThis(); // window 

const arrowPrintThis = () => {
    console.log(this); 
}

arrowPrintThis(); 

console.log(this) // window

참조한 사이트

[Javascript] this와 바인딩
Node에서의 this

반응형

댓글