
ES6 문법에서
const self = this는 너무 못생겼거든. 대안이 없을까?
const self = this;
window.addEventListener('keydown', function (e) {
console.log(e);
console.log(self);
if (e.key === 'ArrowRight') {
self.mainElm.setAttribute('data-direction', 'right');
} else if (e.key === 'ArrowLeft') {
self.mainElm.setAttribute('data-direction', 'left');
}
});
언제나 대안은 있다!!! ✨🫶
Arrow Function은 함수를 간결하게 정의할 수 있는 문법으로, 함수가 호출될 때의 this 컨텍스트가 정적으로 결정됨. 주로 콜백 함수나 메서드 정의 시 this 바인딩 문제를 해결하기 위해 사용됨.
- 함수 본연의 기능을 아주 잘 수행!
- 소괄호, 중괄호 생략 가능
- 내부에서 this값을 쓸 때 밖에 있던 this값을 그대로 사용 (arrow function 쓰는 핵심 이유!!!)
함수는 쓰인 위치에 따라서 내부의 this값이 변하는데, arrow function은 어디서 쓰든간에 내부의 this 값을 변화시키지 않음
즉, Arrow Function을 사용하면 외부의 this 컨텍스트가 유지됨. 따라서 메서드 내부에서 this를 사용할 때 별도의 변수에 할당할 필요가 없음!
최종정리!!
Arrow Function 내부에서 this를 사용하면, 함수가 정의된 시점의 외부 컨텍스트를 유지하게 됨
window.addEventListener('keydown', (e) => {
console.log(e);
console.log(this); // 여기서 this는 클래스의 인스턴스를 가리킵니다.
if (e.key === 'ArrowRight') {
this.mainElm.setAttribute('data-direction', 'right');
} else if (e.key === 'ArrowLeft') {
this.mainElm.setAttribute('data-direction', 'left');
}
});
bind 메서드를 사용하여 콜백 함수 내에서 this를 명시적으로 바인딩할 수 있음
window.addEventListener('keydown', function (e) {
console.log(e);
console.log(this);
if (e.key === 'ArrowRight') {
this.mainElm.setAttribute('data-direction', 'right');
} else if (e.key === 'ArrowLeft') {
this.mainElm.setAttribute('data-direction', 'left');
}
}.bind(this));
ES2022부터 도입된 클래스 필드 문법을 사용하면 더욱 간편하게 this를 사용할 수 있음. 메서드를 Arrow Function으로 정의하면 자동으로 외부 this를 캡처하게 됨.
class Character {
constructor(info) {
// constructor code...
window.addEventListener('keydown', (e) => {
console.log(e);
console.log(this);
if (e.key === 'ArrowRight') {
this.mainElm.setAttribute('data-direction', 'right');
} else if (e.key === 'ArrowLeft') {
this.mainElm.setAttribute('data-direction', 'left');
}
});
}
// other methods...
}
가장 간결하고 일반적으로 사용됨. 클래스 내에서 메서드를 정의할 때 자주 사용됨
ES6 이전 문법과의 호환성을 고려할 때 유용할 수 있음.
가장 현대적이고 간결한 방법이지만, 아직 모든 환경에서 지원되지 않을 수 있음.
const person = {
firstName: 'John',
lastName: 'Doe',
fullName: () => {
console.log(this.firstName + ' ' + this.lastName); // Arrow Function에서의 this는 외부 컨텍스트에 영향을 받음
}
};
person.fullName(); // 출력: undefined undefined (this는 전역 객체를 가리킴)
위 예제에서 fullName 함수는 Arrow Function으로 정의되었기 때문에 this는 전역 객체를 가리키게 됨. Arrow Function은 bind() 메서드를 사용하지 않기 때문에 this를 명시적으로 바인딩할 수 없음.
따라서 프로젝트의 환경과 개발 스타일에 따라 적절한 방법을 선택하여 사용하면 됨. Arrow Function을 사용하는 것이 일반적으로 권장되는 방법이며, bind 메서드는 ES6 이전 코드와의 호환성을 유지할 때 유용할 수 있음.
bind() 메서드를 사용하여 this를 바인딩하면 해당 함수의 실행 컨텍스트에서 항상 지정된 this 값이 유지됨.Arrow Function은 함수가 정의될 때 외부 컨텍스트를 캡처하며, bind() 메서드와 달리 명시적으로 this를 바인딩할 수 없음