[JS] call, apply, bind 메서드
함수 안에서 this를 사용하면 window 객체를 참조하게 된다. 이때 call, apply, bind를 사용하면 참조하는 객체를 바꿀 수 있다.
1. call 메서드
call 메서드는 함수를 호출하는 함수이며, 첫 번째 인수로 값을 전달해 주면, 호출되는 함수의 this는 window 객체가 아닌 전달받은 값을 가리키게 된다.
const fullName = function(){
console.log(this.firstName + " " + this.lastName);
}
fullName();
이 상태로 출력하면 undefined가 출력된다. 왜냐하면 함수 내에서 this는 window객체를 가리키는데, 이때 window객체 내에 firstName라는 메서드가 없기 때문이다.
이런 상황에서 call 메서드를 사용해서 참조하는 객체를 변경해 줄 수 있다.
const fullName = function(){
console.log(this.firstName + " " + this.lastName);
}
const person = {
firstName : "YONGJIN",
lastName: "LEE",
}
fullName.call(person);
다음과 같이 call 메서드의 첫 번째 인수로 person를 넣어주면, 이제 fullName 함수 내의 this는 window객체를 참조하는 것이 아닌, 전달된 person 객체를 참조하게 된다. undefined가 아니라 잘 출력되는 것을 확인할 수 있다.
2. apply 메서드
call 메서드와 비슷하지만 첫 번째 인수 이후 부분을 배열로 넣어주는 차이점이 있다.
const fullName = function(fruits,veg){
console.log(`${this.firstName} ${this.lastName} ${fruits} ${veg}`);
}
const person = {
firstName : "YONGJIN",
lastName: "LEE",
}
fullName.apply(person,['apple','carrot']);
3. bind 메서드
bind 메서드는, 넘겨받은 인수를 바탕으로 함수가 가리키는 this의 값을 변경하고, 새로운 함수를 반환한다. 호출은 하지 않는다.
function func(language){
if(language === 'kor'){
console.log(`language: ${this.korGreeting}`);
}else{
console.log(`language: ${this.engGreeting}`);
}
}
func()
다음과 같은 상황에서 this는 함수 내에 있으므로, undefined를 반환한다.
function func(language){
if(language === 'kor'){
console.log(`language: ${this.korGreeting}`);
}else{
console.log(`language: ${this.engGreeting}`);
}
}
const greeting = {
korGreeting: "하잉",
engGreeting: "hing",
};
const boundFunc = func.bind(greeting);
이때 func 함수에 bind 메서드를 통해 greeting을 인수로 전달한다. 그러면 변수 boundFunc에 this를 greeting으로 참조하는 새로운 함수가 반환된다.
function func(language){
if(language === 'kor'){
console.log(`language: ${this.korGreeting}`);
}else{
console.log(`language: ${this.engGreeting}`);
}
}
const greeting = {
korGreeting: "하잉",
engGreeting: "hing",
};
const boundFunc = func.bind(greeting);
boundFunc('kor');
boundFunc에 ‘kor’을 인수로 넣어주면 해당 값인 language: 하잉 이 잘 출력되는 것을 확인할 수 있다.