ES6 함수의 구분과 특징 정리
ES6에서 함수는 일반 함수, 메서드, 화살표 함수로 나눌 수 있다. 각각은 constructor, prototype, super, arguments 지원 여부가 다르다.
구분 | constructor | prototype | super | arguments |
일반함수 | O | O | X | X |
메서드 | X | X | O | O |
화살표함수 | X | X | X | X |
1. 메서드
ES6 사양에서 메서드는 메서드 축약 표현으로 정의된 함수만을 의미한다.
const obj = {
foo() {
console.log("메서드");
},
};
인스턴스를 생성할 수 없는 non-constructor
prototype프로퍼티가 없음[[HomeObject]]를 가지며, 이를 통해super키워드 사용 가능arguments객체 사용 가능
예시:
const parent = {
say() {
return "부모";
}
};
const child = {
say() {
return super.say() + " → 자식";
}
};
Object.setPrototypeOf(child, parent);
console.log(child.say()); // 부모 → 자식
2. 화살표 함수
화살표 함수는 기존 함수보다 간결하게 작성할 수 있다.
const add = (a, b) => a + b;
특징:
non-constructor
this,arguments,super,new.target을 자체적으로 바인딩하지 않음lexical this: 자신을 둘러싼 상위 스코프의
this를 그대로 참조중복된 매개변수 이름 선언 불가
arguments가 없어 rest 파라미터 사용 필요
예시:
function normal() {
console.log(this); // 호출 방식에 따라 다름
}
const arrow = () => {
console.log(this); // 상위 스코프의 this
};
const obj = {
normal,
arrow
};
obj.normal(); // obj
obj.arrow(); // 전역 객체(window / globalThis)
3. 화살표 함수 vs 일반 함수
항목 일반 함수 화살표 함수
constructor 여부 | O | X |
| 동적 바인딩 (호출 방식에 따라 달라짐) | 상위 스코프의 |
| O | X (상위 스코프 참조) |
| X | 상위 스코프 참조 |
4. rest 파라미터와 arguments
일반 함수 / 메서드 →
arguments객체와rest 파라미터모두 사용 가능화살표 함수 →
arguments없음 → 가변 인자를 처리하려면rest 파라미터만 사용해야 함
예시:
function normal(a, b) {
console.log(arguments); // [Arguments] { '0': 1, '1': 2 }
}
normal(1, 2);
const arrow = (...args) => {
console.log(args); // [1, 2]
};
arrow(1, 2);
5. This 비교
// 전역 this
console.log("전역:", this);
function normal() {
console.log("일반 함수:", this);
}
const arrow = () => {
console.log("화살표 함수:", this);
};
const obj = {
name: "obj",
normal,
arrow,
method() {
console.log("메서드:", this);
},
};
normal(); // 전역 객체
arrow(); // 전역 객체 (lexical this)
obj.normal(); // obj
obj.arrow(); // 전역 객체 (obj 아님!)
obj.method(); // obj
new normal(); // 새 인스턴스일반 함수 | 호출 방식에 따라 동적 |
메서드 | 호출한 객체 |
화살표 함수 | 상위 스코프의 this(lexical) |