class 의 method로서의 함수를 정의 할 때,
화살표 함수로 정의
arrowFunc = () => {
console.log(this);
}
화살표 함수는 자신의 this context를 생성하지 않는다. 대신, 화살표 함수가 정의된 위치(상위 scope)의 this를 상속받는다.
class의 instance를 생성할 때, 화살표 함수는 해당 instance의 this를 그대로 사용한다.
arrowFunc는 class의 instance가 생성되는 시점에 이미 instance에 바로 추가된다. 마치 constructor의 내부에서 this.arrowFunc = () => {} 로 정의 된 것과 같다.
결과적으로 arrowFunc는 instance의 자체 property가 된다.
따라서 instance를 출력할 때 arrowFunc도 출력이 된다.
예)
일반 함수로 정의
regularFunc = function () {
console.log(this);
}
일반 함수는 this context를 가지고 있다. 즉, 해당 함수가 어떻게 호출되는지에 따라 결정된다.
그냥 method로 정의
methodFunc() {
console.log(this);
}
methodFunc는 prototype method로 정의되며, instance 자체가 아닌 class의 prototype에 저장된다. 따라서 instance에 직접 포함이 되지는 않고, 대신 class이름.prototype.methodFunc 으로 접근된다.
이는 메모리 효율성을 높이기 위해 javascript가 prototype 상속을 사용하는 방법이다.