프론트엔드 개발/Javascript

자바스크립트 - call, apply, bind

snowman95 2021. 8. 21. 20:52
728x90
반응형

call, apply, bind


객체 밖에 선언된 함수가 특정 객체의 프로퍼티를 다룰때 사용된다.

객체 밖에 선언되어 있으니 함수 내의 this가 무엇인지를 알 수 없는 상태인데

call/apply/bind 함수를 사용하여 this가 누군지 명시적으로 알려줄 수 있다.

 

call

인수를 개별적으로 받는다.

const user1={
  name:"sponge",
};
const user2={
  name:"bob",
};

function showInfo(){
  console.log(this.name);
}
showInfo.call(user1); → this에 user1 객체 들어감
showInfo.call(user2); → this에 user2 객체 들어감

function changeInfo(age, gender){
  this.age = age;
  this.gender = gender;
}
changeInfo.call(user1, 50, "male"); → this에 user1 객체 들어감

 

apply

인수를 배열로 받는다. call과 동작은 동일함.

const user1={
  name:"sponge",
};
const user2={
  name:"bob",
};

function changeInfo(age, gender){
  this.age = age;
  this.gender = gender;
}
changeInfo.apply(user1, [50, "male"]); → this에 user1 객체 들어감

 

bind

함수의 this를 특정 객체로 바인딩 해버린다.

 

const user1={
  name:"sponge",
};

function changeInfo(age, gender){
  this.age = age;
  this.gender = gender;
}

const changeUserInfo = changeInfo.bind(user1); → this에 user1 객체가 바인딩됨
changeUserInfo(50, "male"); → this는 user1

 

반응형