arrow function this binding

fpg1·2024년 4월 21일

모던 자바스크립트 Deep Dive 7쇄 485p~
26. _ES6 함수의 추가 기능

class Person {
  	constructor() {
      this.name = 'Lee';
      this.sayHi = () => console.log(`Hi ${this.name}`);
    }
}

sayHi 클래스 필드에 할당한 화살표 함수의 상위 스코프는 사실 클래스 외부다. 하지만 this는 클래스 외부의 this를 참조하지 않고 클래스가 생성할 인스턴스를 참조한다 (중략)

  • 왜 화살표 함수의 상위 스코프(클래스외부)를 참조하지 않고 클래스가 생성할 인스턴스를 참조하는지 이유가 나와있지 않다.

 mdn 문서: Functions > Arrow function expressions
(링크)

class C {
  a = 1;
  autoBoundMethod = () => {
  	console.log(this.a);
  };
}

const c = new C();
c.autoBoundMethod(); // 1
const { autoBoundMethod } = c;
autoBoundMethod();	// 1

Because a class's body has a this context, arrow functions as class fields close over the class's this context, and the this inside the arrow function's body will correctly point to the instance (or the class itself, for static fields). However, because it is a closure, not the function's own binding, the value of this will not change based on the execution context.

  • 화살표 함수의 상위 스코프가 생성된 인스턴스를 참조하는 이유를 설명하고 있다
    화살표 함수는 클래스의 this context 닫혀(closure)
    생성된 인스턴스를 참조하는 것

  • 하지만 디버깅하여 살펴보면 autoBoundMethod 메소드의 상위 스코프는 클래스 외부가 맞으며, closure가 나오지 않는다. 다만 this의 값이 인스턴스를 참조할 뿐
profile
backend

0개의 댓글