티스토리 뷰

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


call

모든 함수에서 사용할 수 있으며, this를 특정값으로 지정할 수 있음

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

const tom = {
  name: 'Tom',
};

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

showThisName(); // window.name
showThisName.call(mike); // 'Mike'
showThisName.call(tom); // 'Tom'

 

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

const tom = {
  name: 'Tom',
};

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

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

// call을 사용할 함수.call(this로 사용할 값, call을 사용할 함수의 인자)
update.call(mike, 1999, 'singer');
console.log(mike); // {name: 'Mike', birthYear: 1999, occupation: 'singer'}

 


apply

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

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

배열요소를 함수의 매개변수로 이용할 때 사용

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

const tom = {
  name: 'Tom',
};

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

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

// 같은 결과를 얻을 수 있음
update.call(mike, 1999, 'singer');
console.log(mike); // {name: 'Mike', birthYear: 1999, occupation: 'singer'}'

update.apply(mike, [1999, 'singer']);
console.log(mike); // {name: 'Mike', birthYear: 1999, occupation: 'singer'}

두번째 매개변수로 배열을 전달하면 그 요소들을 차례로 사용

// 제일 큰 수, 작은 수 구하기
const nums = [2, 10, 34, 6, 7];

const maxNum = Math.max.apply(null, nums); // 딱히 this가 필요하지않아서 null을 넣음
const minNum = Math.min.apply(null, nums);

console.log(maxNum); // 34
console.log(minNum); // 2

apply와 call의 다른 점

apply : 배열을 매개변수로 받고

call : 배열의 요소들을 직접 매개변수로 받음

// 제일 큰 수, 작은 수 구하기
const nums = [2, 10, 34, 6, 7];

const maxNum = Math.max.apply(null, nums);
// = Math.max.apply(null, [2, 10, 34, 6, 7]); // apply는 배열을 받고

const minNum = Math.min.call(null, nums);
// = Math.min.apply(null, 2, 10, 34, 6, 7); // call은 각각 요소를 받음

bind

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

const user = {
  name: 'Mike',
  showName: function () {
    console.log(`hello, ${this.name}`);
  },
};

user.showName(); // hello, Mike

let fn = user.showName; // 이렇게 할당하면 this를 잃게 됨

fn(); // hello, => 그래서 이름이 출력되지 않음

 

const user = {
  name: 'Mike',
  showName: function () {
    console.log(`hello, ${this.name}`);
  },
};

user.showName(); // hello, Mike

let fn = user.showName;

fn(); // hello, 

let boundFn = fn.bind(user); // bind를 해주면 user를 this로 사용

boundFn(); // hello, Mike

+ 추가

 

call, apply는 함수를 실행하지만 bind는 함수를 실행하지 않음

const user = {
  name: 'Mike',
  age : 20,
  greeting: function () {
    console.log(`hello, ${this.name}, ${this.age}`);
  },
  update : function(age) {
  this.age = age;
  }
};

user.greeting.bind(user); //
user.greeting.call(user); // "hello, Mike, 20"
user.greeting.apply(user); // "hello, Mike, 20"

user.update.bind(user, 40)
console.log(user)
// {
//  age: 20,
//  greeting: function () {
//    console.log(`hello, ${this.name}, ${this.age}`);
//  },
//  name: "Mike",
//  update: function(age) {
//  this.age = age;
//  }
// }

user.update.call(user, 40)
console.log(user)
// {
//  age: 40,
//  greeting: function () {
//    console.log(`hello, ${this.name}, ${this.age}`);
//  },
//  name: "Mike",
//  update: function(age) {
//  this.age = age;
//  }
//}

user.update.apply(user, [40])
console.log(user)
// {
//  age: 40,
//  greeting: function () {
//    console.log(`hello, ${this.name}, ${this.age}`);
//  },
//  name: "Mike",
//  update: function(age) {
//  this.age = age;
//  }
//}

 

 

bind를 해준 함수를 실행하면 실행됨

const binding = user.update.bind(user, 40)
binding();
console.log(user)
// {
//  age: 20,
//  greeting: function () {
//    console.log(`hello, ${this.name}, ${this.age}`);
//  },
//  name: "Mike",
//  update: function(age) {
//  this.age = age;
//  }
// }
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함