call, apply, bind

Jaeseok Han·2023년 3월 11일

javascript 문법

목록 보기
6/11

1. call, apply, bind를 사용하는 이유

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

2. call

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

const mike = {
  name : "Mike"
}

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

showThisName(); //  (this = window)
showThisName.call(mike); // Mike (this = mike)

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

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

3. apply

함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같음
call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받음

const mike = {
  name : "Mike"
}

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

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

배열을 함수 매개변수로 받을 때 유용

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");
console.log(mike); // {name : "Mike", birthYear : 1980, occupation : "police"}

5. 사용 예제

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

let fn = user.showName;
fn(); // hello, (this 를 잃어버림)

fn.call(user); //hello, Mike
fn.apply(user); //hello, Mike

let boundFn = fn.bind(user);
boundFn(); //hello, Mike

0개의 댓글