앞서 this 키워드를 다룬 글에서
this 바인딩(= this가 가리키는 값)은 함수 호출 방식에 의해 동적으로 결정된다고 했다
this 바인딩은 함수의 메서드로 call, apply, bind를 사용하면 명시적으로 설정할 수도 있다
call : 첫 번째 인자로 this를 설정하고, 나머지 인자를 개별적으로 전달한다
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const user = { name: 'Charlie' };
// call: 인자를 개별적으로 전달
greet.call(user, 'Hello', '!'); // 'Hello, Charlie!' 출력 (this가 user로 설정됨)
apply : 첫 번째 인자로 this를 설정하고, 두 번째 인자로 배열을 전달한다
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const user = { name: 'Charlie' };
// apply: 인자를 배열로 전달
greet.apply(user, ['Hi', '.']); // 'Hi, Charlie.' 출력 (this가 user로 설정됨)
bind : 첫 번째 인자로 this를 설정하고, 새로운 함수가 반환되며 이를 나중에 호출할 때도 설정된 this가 유지된다
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const user = { name: 'Charlie' };
// bind: 인자를 미리 설정하고 새로운 함수 반환
const greetUser = greet.bind(user, 'Good morning', '!!');
greetUser(); // 'Good morning, Charlie!!' 출력 (this가 user로 설정됨)
위의 예시와 같이 bind 메서드를 사용하면 this뿐만 아니라 다른 인자도 함께 기억한다
'Javascript' 카테고리의 다른 글
| 비동기 처리 (1) | 2024.10.25 |
|---|---|
| JavaScript 특성 (0) | 2024.10.25 |
| this 키워드 (0) | 2024.10.13 |
| 클로저(Closure)란? (1) | 2024.10.05 |
| 함수 선언문과 함수 표현식 (0) | 2024.10.04 |