call, apply, bind

허성진·2021년 10월 3일
0

call, apply, bind
함수 호출방식과 관계없이 this를 지정할 수 있음

call

call멧서드는 모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할수 있습니다.

const Mike = {
  name: "Mike",
};

const Tom = {
  name: "Tom",
};

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

showThisName.call(Mike); // Mike

showThisName.call(Tom); // Tom

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

  this.occupation = occupation;
}

update.call(Mike, 1999, "singer"); // {name:"Mike", birthYear: 1999, occupation: "singer"}

update.call(Tom, 2002, "teacher"); // {name:"Tom", birthYear: 2002, occupation: "teacher"}

apply

appl는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같습니다

call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받습니다

update.apply(Mike, [1999, "singer"]); // {name:"Mike", birthYear: 1999, occupation: "singer"}

update.apply(Tom, [2002, "teacher"]); // {name:"Tom", birthYear: 2002, occupation: "teacher"}

const nums = [3, 10, 1, 6, 4];

const minNum = Math.min(...nums); //1

const maxNum = Math.max(...nums); //10

const minNum = Math.min.apply(null, nums); //1 배열로 받는다

// = Math.min.apply(null, [3,10,1,6,4])

const minNum = Math.max.call(null, nums); //10

// = Math.min.call(null, 3,10,1,6,4)

bind

함수의 this 값을 영구히 바꿀수 있다

const mike = {
  name: "Mike",
};

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

  this.occupation = occupation;
}

const updateMike = update.bind(mike);

updateMike(1980, "police"); // {name:"Mike", birthYear: 1980, occupation: "police"}

const user = {
  name: "Mike",

  showName: function () {
    consloe.log(`Hello, ${this.name}`);
  },
};

user.showName(); //Hello, Mike

let fn = user.showName;

(fn = Hello), fn.call(user); //Hello, Mike

fn.apply(user); //Hello, Mike

let boundFn = fn.bind(user); //Hello, Mike
profile
궁굼하면 눌러봐

0개의 댓글