본문 바로가기

개발면접/자바스크립트 문제

Q3. this키워드 화살표함수와 일반함수의 차이

 

 

무엇이 출력될까요?

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2
  },
  perimeter: () => 2 * Math.PI * this.radius,
}
 
console.log(shape.diameter())
console.log(shape.perimeter())

 

아래를 열면, 정답이 보인다.

더보기

첫번째 콘솔로그는 일반함수이기 때문에, this가 shape 객체를 가리켜 20이 찍힐것이다.

 

두번째 콘솔로그는 화살표함수임에 유의해야한다.

화살표함수에서는 this키워드가 상위스코프의 this를 상속받는다는 개념과 bind메소드가 실행되지 않는다.

따라서, perimeter에서의 this객체는 상위 스코프인 글로벌, 즉 window객체를 가리키게 된다.

window객체는 radius라는 키값이 없기 때문에, 2 * 3.14 * undefined가 되어 NaN이 찍힌다.

 

 

 

 

 

 


 

 

참조하기 좋은 자료

https://www.youtube.com/watch?v=PAr92molMHU 

 

https://poiemaweb.com/es6-arrow-function

 

Arrow function | PoiemaWeb

Arrow function(화살표 함수)은 function 키워드 대신 화살표(=>)를 사용하여 간략한 방법으로 함수를 선언할 수 있다. 하지만 모든 경우 사용할 수 있는 것은 아니다. 문법은 아래와 같다.

poiemaweb.com