Javascript-13 (call, apply, bind)

Patrick·2021년 4월 19일
1

Javascript

목록 보기
13/18
post-thumbnail

Javascript를 사용하다보면 어김 없이 볼 수 있는 것이 바로 this 라는 것이다.
다음에 this에 대해서 조금 더 자세하게 다뤄보겠지만, 우선 this를 바인딩 하는 방법인 call, apply, bind에 대해서 정리해보자!

Javascript에서 call, apply, bind는 함수 호출 방식과 관계 없이 this가 무엇인지 지정할 수 있다.

call

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

const mike = {
  name: "MIKE"
};

const tom = {
  name: "TOM"
};

function showThisName() {
  console.log(this.name);
  // this는 window를 가리킴
}

showThisName(); // 아무것도 출력되지 않음

이 때 console.log의 this는 window 전역객체를 가리키는데, window.name이 빈 문자열이기 때문에 아무것도 출력 되지 않는다.

const mike = {
  name: "MIKE"
};

const tom = {
  name: "TOM"
};

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

showThisName.call(mike);  // "MIKE"
showThisName.call(tom);  // "TOM"

이렇게 call을 사용하고 this로 사용할 객체를 넘기면 해당 함수가 주어진 객체의 메소드인것처럼 사용이 가능하다.

apply

: 함수 매개변수를 처리하는 방법을 제외하면, call과 완전히 같다
: call은 일반적인 함수처럼 매개변수를 직접 받지만, apply는 배열로 받는다
: 배열요소를 함수 매개변수로 사용 할 때 사용하기 좋다

const mike = {
  name: "MIKE"
};

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

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

update.apply(mike, [1999, "singer"]);

console.log(mike);
  • call과 같지만 mike 이후 부분을 배열( [ ] )로 감싼다

bind

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

const mike = {
  name: "MIKE"
};

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

const updateMike = update.bind(mike);

updateMike(1980, "teacher");
console.log(mike);
  • this 값을 항상 mike로 만들려면 위와 같이 하면 된다!!
  • bind는 새로운 binding 함수를 하나 만드는데, 이 함수는 항상 mike를 this로 받는다
const user = {
  name: 'MIKE',
  showName: function() {
    console.log(`hello, ${this.name}`);
  },
};

user.showName(); // hello, Mike

let fn = user.showName;

fn.call(user); // hello, MIKE
fn.apply(user); // hello, MIKE 
let boundFn = fn.bind(user);
boundFn(); // hello, MIKE 
  • fn에 .call 혹은 .apply 를 하고 this로 사용 할 값 user를 넣어주면 제대로 출력된다
  • bind 또한 user를 this 값으로 갖도록 하면 똑같이 출력된다
profile
예술을 사랑하는 개발자

0개의 댓글