call 메소드는 함수를 호출할 때 this를 지정할 수 있게 해준다. 인자는 첫 번째로 this로 사용할 객체를, 그 다음은 함수에 전달할 인자들을 나열한다.
function greet() {
console.log(`Hello, ${this.name}`);
}
const user = { name: 'Alice' };
greet.call(user); // "Hello, Alice"
apply 메소드는 call과 비슷하지만, 함수에 전달할 인자를 배열로 받는다. 따라서 여러 인자를 동시에 전달할 때 유용하다.
function introduce(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const user = { name: 'Bob' };
introduce.apply(user, ['Hi', '!']); // "Hi, Bob!"
bind 메소드는 함수를 호출하지 않고, 새로운 함수를 생성하여 this 값을 고정한다. 이 새로운 함수는 나중에 호출할 수 있다.
function showName() {
console.log(this.name);
}
const user = { name: 'Charlie' };
const boundShowName = showName.bind(user);
boundShowName(); // "Charlie"
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);
const intervalId = setInterval(() => {
console.log("Hello every second");
}, 1000);
// 중지하려면 clearInterval(intervalId) 사용
화살표 함수는 자신만의 this 값을 가지지 않기 때문에 상위 스코프의 this를 유지한다.
const obj = {
name: 'Diana',
greet() {
setTimeout(() => {
console.log(`Hello, ${this.name}`);
}, 1000);
}
};
obj.greet(); // "Hello, Diana" (1초 후)