자바스크립트에서 함수 정의 방식에는 일반 함수와 화살표 함수 두 가지가 있습니다. 이 두 함수 정의 방식의 주요 특징은 다음과 같습니다:
일반 함수와 화살표 함수의 가장 큰 차이는 this의 바인딩 방식이며, 이를 이해하고 적절히 사용하면 코드의 가독성을 높이고 문제를 방지할 수 있습니다. 일반 함수는 동적으로 this가 바인딩되지만, 화살표 함수는 정의된 시점에서의 외부 스코프의 this를 유지하므로 작성한 코드의 의도대로 this가 동작하도록 할 수 있습니다.
1) 오류 : 일반 함수 사용으로
class Counter {
constructor() {
this.count = 0;
document.getElementById('incrementBtn').addEventListener('click', this.increment);
}
increment() {
this.count++;
console.log(this.count);
document.getElementById('countDisplay').innerText = this.count;
}
}
const counter = new Counter();
위의 코드에서 Counter 클래스의 increment 메서드 내에서 this.count를 사용하여 count 값을 증가시키고 DOM에 반영하려고 하지만, this가 Counter 인스턴스를 가리키지 않아서 오류가 발생합니다. increment 메서드가 일반 함수로 정의되어 있기 때문에 이 문제가 발생하는 것입니다.
해결 방법으로는 increment 메서드를 화살표 함수로 변경하여 this가 Counter 인스턴스를 가리키도록 수정할 수 있습니다. 아래와 같이 코드를 수정해보겠습니다:
2) 해결 : 화살표 함수 사용
class Counter {
constructor() {
this.count = 0;
document.getElementById('incrementBtn').addEventListener('click', this.increment);
}
increment = () => { // 화살표 함수로 변경
this.count++;
console.log(this.count);
document.getElementById('countDisplay').innerText = this.count;
}
}
const counter = new Counter();
위와 같이 increment 메서드를 화살표 함수로 변경하면 this가 Counter 인스턴스를 가리키므로 문제가 해결됩니다. 이제 increment 메서드 내에서 정확히 Counter 인스턴스의 count 값을 증가시키고 DOM에 반영할 수 있게 됩니다.
this.onClick = this.onClick.bind(this); this.onclick는 this.onClick에 bind하라 뭣을 현재(this)를 현재는 class임.
JavaScript에서 this는 함수가 호출될 때 바인딩되는 특별한 키워드이며, 함수가 어떻게 호출되는지에 따라 this가 가리키는 대상이 달라집니다. 이를 이해하기 위해서는 this의 바인딩 방식을 구체적으로 알아야 합니다.
예시:
function greet() {
console.log(this.name);
}
const person = { name: 'Alice' };
person.greet = greet;
greet(); // undefined
person.greet(); // 'Alice'
예시:
const person = {
name: 'Bob',
greet: () => {
console.log(this.name);
}
};
person.greet(); // undefined
이 예시에서 화살표 함수 greet는 person 객체의 메서드이지만, this가 상위 스코프인 전역 객체를 가리키기 때문에 name에 접근할 수 없습니다. 화살표 함수는 bind, apply, call을 통한 this 바인딩이 불가능하며, 외부 스코프의 this를 그대로 사용합니다.
이렇게 this의 바인딩 방식에 대해 이해하고 적절히 활용하면 코드 작성 시 발생할 수 있는 오류를 방지할 수 있습니다. 함수를 어떻게 정의하느냐에 따라 this가 어디를 가리키는지를 주의깊게 확인하는 것이 중요합니다.