모던 자바스크립트 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.
autoBoundMethod 메소드의 상위 스코프는 클래스 외부가 맞으며, closure가 나오지 않는다. 다만 this의 값이 인스턴스를 참조할 뿐