[JS] call, apply, bind 메서드

2024. 4. 25. 17:55·프로그래밍 언어/JavaScript
목차
  1. 1. call 메서드
  2. 2. apply 메서드
  3. 3. bind 메서드

함수 안에서 this를 사용하면 window 객체를 참조하게 된다. 이때 call, apply, bind를 사용하면 참조하는 객체를 바꿀 수 있다.

 

 

 

1. call 메서드

call 메서드는 함수를 호출하는 함수이며, 첫 번째 인수로 값을 전달해 주면, 호출되는 함수의 this는 window 객체가 아닌 전달받은 값을 가리키게 된다.

 

const fullName = function(){
  console.log(this.firstName + " " + this.lastName);
}

fullName();

이 상태로 출력하면 undefined가 출력된다. 왜냐하면 함수 내에서 this는 window객체를 가리키는데, 이때 window객체 내에 firstName라는 메서드가 없기 때문이다.

 

이런 상황에서 call 메서드를 사용해서 참조하는 객체를 변경해 줄 수 있다.

 

 

 

 

const fullName = function(){
  console.log(this.firstName + " " + this.lastName);
}

const person = {
  firstName : "YONGJIN",
  lastName: "LEE",
}

fullName.call(person);

다음과 같이 call 메서드의 첫 번째 인수로 person를 넣어주면, 이제 fullName 함수 내의 this는 window객체를 참조하는 것이 아닌, 전달된 person 객체를 참조하게 된다.  undefined가 아니라 잘 출력되는 것을 확인할 수 있다. 

 

 

 

 

2. apply 메서드

call 메서드와 비슷하지만 첫 번째 인수 이후 부분을 배열로 넣어주는 차이점이 있다.

 

const fullName = function(fruits,veg){
  console.log(`${this.firstName} ${this.lastName} ${fruits} ${veg}`);
}

const person = {
  firstName : "YONGJIN",
  lastName: "LEE",
}

fullName.apply(person,['apple','carrot']);

 

 

 

 

3. bind 메서드

bind 메서드는, 넘겨받은 인수를 바탕으로 함수가 가리키는 this의 값을 변경하고, 새로운 함수를 반환한다. 호출은 하지 않는다.

 

function func(language){
  if(language === 'kor'){
    console.log(`language: ${this.korGreeting}`);
  }else{
    console.log(`language: ${this.engGreeting}`);
  }
}

func()

다음과 같은 상황에서 this는 함수 내에 있으므로, undefined를 반환한다. 

 

 

 

 

function func(language){
  if(language === 'kor'){
    console.log(`language: ${this.korGreeting}`);
  }else{
    console.log(`language: ${this.engGreeting}`);
  }
}

const greeting = {
  korGreeting: "하잉",
  engGreeting: "hing",
};

const boundFunc = func.bind(greeting);

이때 func 함수에 bind 메서드를 통해 greeting을 인수로 전달한다. 그러면 변수 boundFunc에 this를 greeting으로 참조하는 새로운 함수가 반환된다.

 

 

 

 

function func(language){
  if(language === 'kor'){
    console.log(`language: ${this.korGreeting}`);
  }else{
    console.log(`language: ${this.engGreeting}`);
  }
}

const greeting = {
  korGreeting: "하잉",
  engGreeting: "hing",
};

const boundFunc = func.bind(greeting);
boundFunc('kor');

boundFunc에 ‘kor’을 인수로 넣어주면 해당 값인 language: 하잉 이 잘 출력되는 것을 확인할 수 있다. 

'프로그래밍 언어 > JavaScript' 카테고리의 다른 글

[JS] 클로저  (2) 2024.04.25
[JS] 이벤트 루프  (0) 2024.04.25
[JS] this 키워드  (0) 2024.04.25
[JS] id를 반환받지 않아도 Script에서 바로 지목할 수 있다.  (0) 2024.04.24
[JS] 이벤트 버블링, 이벤트 캡처링  (0) 2024.04.24
  1. 1. call 메서드
  2. 2. apply 메서드
  3. 3. bind 메서드
'프로그래밍 언어/JavaScript' 카테고리의 다른 글
  • [JS] 클로저
  • [JS] 이벤트 루프
  • [JS] this 키워드
  • [JS] id를 반환받지 않아도 Script에서 바로 지목할 수 있다.
tteokbokki-master
tteokbokki-master
공부하며 알아가는 걸 조금씩 정리하고 있어요
  • tteokbokki-master
    용로그
    tteokbokki-master
  • 전체
    오늘
    어제
    • 분류 전체보기
      • 프로그래밍 언어
        • HTML & CSS
        • JavaScript
        • React 기초
        • 파이썬 기초
        • TanStack-Query
        • C언어 기초
        • git
        • 리눅스
        • 코딩테스트 공부
      • 개발 지식
      • 회고 및 기록
      • 프로젝트
        • TodoList 만들기
        • 학수고대 프로젝트
      • 기타
        • [JS-0기] 한입 FE 챌린지
  • 인기 글

  • 글쓰기 / 관리
  • hELLO· Designed By정상우.v4.10.3
tteokbokki-master
[JS] call, apply, bind 메서드
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.