
자바스크립트에 함수는 일급 객체로서 매우 유연하고 강력한 기능을 제공한다. 이러한 특성 덕분에 고차 함수로 활용할 수 있고, 함수형 프로그래밍도 가능하다. 하지만 이런 유연성이 때로는 혼란은 가져올 수 있다. 오늘은 자바스크립트 함수의 세 가지 핵심 형태를 살펴보자
function func() {
return this;
}
// 화살표 함수
const arrowFunc = () => {
return this;
};
func(); // this는 window 또는 global (strict mode에서는 undefined)
const obj = {
// 모던한 메서드 축약 표현
method() {
return this;
},
// 전통적인 방식
traditionalMethod: function() {
return this;
}
};
obj.method(); // this는 obj를 가리킴
// 전통적인 생성자 함수
function Person(name) {
this.name = name;
}
// 모던한 클래스 문법
class ModernPerson {
constructor(name) {
this.name = name;
}
}
const person1 = new Person('Alice');
const person2 = new ModernPerson('Bob');
func()obj.method()new Constructor()// 유틸리티 함수 - 독립적인 기능
function calculateTax(amount) {
return amount * 0.1;
}
// 메서드 - 객체와 연관된 기능
const cart = {
items: [],
addItem(item) {
this.items.push(item);
},
getTotalPrice() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
};
// 클래스 - 객체 생성을 위한 템플릿
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
자바스크립트에서 함수의 세 가지 형태를 구분하여 이해하는 것은 매우 중요하다. 특히 this 바인딩과 관련된 부분은 면접에서도 자주 다루어지는 주제이므로, 각 상황에서 this가 어떻게 바인딩 되는지 정확히 이해하는 것이 좋다. 코드를 작성할 때는 각 함수의 목적과 역할을 명확히 하여, 적절한 형태의 함수를 선택하는 것이 깔끔한 코드 작성의 첫 걸음이 될 것이다.