본문 바로가기

Dev/JAVASCRIPT

Javascript JS call / apply / bind

call() - 매개변수를 직접 받음

const mike = {
  name: "Mike"
}

const Tom = {
  name: "Tom"
}

function showThisName() {
  console.log(this.name);
}

showThisName(); // 아무 결과도 업음
showThisName.call(mike); // this가 mike가 되면서 this.name 결과, "Mike"

function update(birthYear, occupation) {
  this.birthYear = birthYear;
  this.occupation= occupation;
}

update.call(mike, 1999, "singer");
console.log(mike); // mike 객체가 업데이트 됨 결과, {"name": "Mike","birthYear": 1999,"occupation": "singer"}

 

apply() - 매개변수를 배열로 받음

const mike = {
  name: "Mike"
}

const Tom = {
  name: "Tom"
}

function update(birthYear, occupation) {
  this.birthYear = birthYear;
  this.occupation= occupation;
}

update.apply(mike, [1999, "singer"]);
console.log(mike); // mike 객체가 업데이트 됨 결과, {"name": "Mike","birthYear": 1999,"occupation": "singer"}

 

bind - 함수의 this 값을 영구히 바꿀 수 있음

const mike = {
  name: "Mike"
}

const Tom = {
  name: "Tom"
}

function update(birthYear, occupation) {
  this.birthYear = birthYear;
  this.occupation= occupation;
}

const updateMike = update.bind(mike);
updateMike(1980, "police");
console.log(mike); // updateMike는 this의 값을 영구히 mike로 바꿈 결과, {"name": "Mike","birthYear": 1980,"occupation": "police"}