call, apply, bind - this값 지정

soyeon·2022년 11월 28일
0

TIL

목록 보기
30/32

https://youtu.be/KfuyXQLFNW4
코딩앙마님 강의 정리

call

  • 모든 함수에서 사용 가능
  • this를 특정값으로 지정
onst mike = {
  name: "Mike"
};
function showThisName() {
  console.log(this.name);
}
showThisName.call(mike); //this === mike

function update(year, occupation) {
  this.birthYear = year;
  this.occupation = occupation;
}
  • 첫번째 인수 = this로 지정할 거
  • 두번째 인수 이후 = 함수의 매개변수
update.call(mike, 1999, "singer");
console.log(mike); //name: "Mike", birthYear: 1999, occupation: "singer"}

apply

  • call과 같은 기능
  • 함수의 배개변수를 배열로 받음
update.apply(mike, [2000, "singer"]);
console.log(mike); //{name: "Mike", birthYear: 2000, occupation: "singer"}

bind

  • 함수의 this 값을 영구히 바꿀 수 있음
const mike = {
  name: "Mike"
};

function update(birthYear, job) {
  this.birthYear = birthYear;
  this.job = job;
}
const updateMike = update.bind(mike);
updateMike(1997, "police");
console.log(mike);
//{name: "Mike", birthYear: 1997, job: "police"}
profile
공부중

0개의 댓글