자바스크립트에서 call, apply, bind는 함수의 this 값을 명시적으로 설정할 때 사용되는 메서드들이다. 세 메서드 모두 함수 객체의 메서드로, this가 가리키는 객체를 원하는 대로 설정할 수 있으며, 특히 bind는 새로운 함수를 반환하는 점이 차이점이다.
call은 함수를 호출하면서 this 값을 지정하고, 매개변수를 개별적으로 전달할 때 사용.
첫 번째 인수로 this로 사용할 객체를 전달하고,
이후에는 함수에 전달할 매개변수들을 순서대로 나열한다.
🖥️ javascript
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const user = { name: "Alice" };
greet.call(user, "Hello", "!"); // "Hello, Alice!"
apply는 call과 유사하지만, 매개변수를 배열로 전달한다.
첫 번째 인수로 this로 사용할 객체를 전달하고,
두 번째 인수로 배열 형태의 인수 목록을 전달.
🖥️ javascript
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const user = { name: "Bob" };
greet.apply(user, ["Hi", "."]); // "Hi, Bob."
➡️ apply는 함수에 여러 개의 인수를 배열로 한 번에 전달해야 할 때 유용하다.
bind는 this를 특정 값으로 고정한 새 함수를 반환한다.
호출 시점이 아닌, 미리 this를 설정해둔 함수를 만들고자 할 때 사용.
call과 apply처럼 바로 호출되지 않고, 반환된 함수를 나중에 호출할 수 있다.
🖥️ javascript
function greet(greeting, punctuation) {
console.log(greeting + ", " + this.name + punctuation);
}
const user = { name: "Charlie" };
const greetUser = greet.bind(user, "Hey", "!");
greetUser(); // "Hey, Charlie!"
➡️ 이처럼 bind는 함수가 호출되는 시점이 아닌,
함수가 정의되는 시점에 this를 설정해 두는 것이 필요할 때 유용하다.