공통점
- this 설정: 둘 다 특정 객체를 this 로 설정하여 함수를 호출할 수 있다.
- 함수 실행: 호출 즉시 실행(즉, 정의만 하지 않고 바로 실행)
- 사용 대상: 함수 객체에 직접 사용
차이점
| 특징 | call() | apply() |
|---|
| 인수 전달 방식 | 개별적으로 나열 (arg1, arg2,…) | 배열 형태로 전달 ([arg1, arg2,…]) |
| 가독성 | 인수가 적을 때 명확 | 인수 배열을 이미 가진 경우 편리 |
| 사용시기 | 인수를 개별적으로 나열하여 호출하는 것이 더 직관적일 때 | 인수 목록을 배열로 관리하거나 기존 배열 데이터를 전달해야 하는 경우 |
call()
- 문법:
function.call(thisArg, arg1, arg2, ...)
- 인수를 개별적으로 나열하여 전달합니다.
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: "Alice" };
greet.call(person, "Hello", "!");
apply()
- 문법:
function.apply(thisArg, [argsArray])
- 인수를 배열 또는 유사 배열 객체로 전달합니다.
- 유사 배열 객체 알아보기
📝
유사 배열 객체 : 배열처럼 동작하지만 배열은 아닌 객체
ex 1) length 속성**:** 몇 개의 항목이 있는지 나타낸다.
ex 2) 숫자 키: 배열처럼 인덱스를 통해 요소에 접근할 수 있다.
❗배열 메서드 없음: 배열의 내장 메서드(forEach, map 등)를 직접 사용할 수 없다.
-Array.from( )으로 유사 배열 객체이 있는 value를 복사해 배열로 만드면 유사 배열 객체도 배열 메서드를 사용할 수 있다.
```jsx
const arrayLike = {
0: "Hello",
1: "World",
length: 2,
};
console.log(arrayLike[0]); // "Hello"
console.log(arrayLike[1]); // "World"
console.log(arrayLike.length); // 2
```
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const person = { name: "Alice" };
greet.apply(person, ["Hello", "!"]);