call, apply, bind

·2024년 8월 6일

자바스크립트

목록 보기
17/21

이전에 한번 정리했었는데 리액트에서 class 컴포넌트를 공부하면서 this 바인딩을 접하면서 다시 한번 리마인드하기 위해서 정리해본다.

call, apply, bind 는 JS에서 특정 함수를 특정 객체의 메서드인 것처럼 사용할 수 있도록 this 값을 변경하며 사용하는 함수의 메서드.

call : this를 바꾸고 인자를 넣어준다.
apply : this를 바꾸고 인자를 배열로 넣어준다.
bind : this를 바꾸고 bound 함수를 반환한다. this를 고정해두고 남은 인자를 따로 받는 부분 적용 함수를 사용할 수 있다.

  const testValue = { name: 'jamong' };
  const test = function (condition) {
    console.log(`hello! ${this.name} ${condition}`);
    console.log(this);
  };
  // call, apply 는 바로 결과 출력
  test.call(testValue, 'good'); //hello! jamong good / {name: 'jamong'}
  test.apply(testValue, ['perfect']); //hello! jamong perfect / {name: 'jamong'}

  // bind는 바로 실행되지 않음
  const testBind = test.bind(testValue);
  console.log(testBind);
  // ƒ (condition) {
  //   console.log(`hello! ${this.name} ${condition}`);
  //   console.log(this);
  // }
  testBind('oh'); //hello! jamong oh / {name: 'jamong'}
  testBind(['yeah']); // hello! jamong yeah / {name: 'jamong'}

  // this를 testValue로 고정한 새로운 함수 반환 (부분 적용 함수!)
  test.bind(testValue)('e~'); // hello! jamong e~
profile
'한 번 더!'의 가능성을 믿어! 오늘도 열심히 굴러가 보는 프론트엔드 개발자 😎

0개의 댓글