ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트 - Call, Bind, Apply 그리고 this
    자바스크립트 JavaScript 2022. 11. 18. 00:31

    Call, Bind, Apply 그리고 this 🏓

     

    함수의 this keyword는 함수가 어떻게 불러지냐에 따라 다릅니다.
    이번 게시물에서는 function의 메소드인 call, apply, bind를 this와 함께 설명합니다.


    0. 함수의 this
    1. call, apply, bind의 차이점
    2. call()
    3. apply()
    4. bind()
    5. bind와 eventListener (feat. this keyword)

     

    📎 reference
    This : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
    Function Prototype: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype

    0. this란? (함수 ver)

    • 함수의 this는 함수 자신을 가르킵니다.

      (화살표 함수는 예외입니다. 화살표 함수의 this는 렉시컬 this, 실행 환경의 this입니다.)
    • this keyword를 통해, 함수가 실행되었을 때의 변수 환경(함수 스코프)에 접근할 수 있습니다.

     

    1. call, apply, bind의 차이점

    • call과 apply, bind는 함수의 메소드입니다. 세 가지 메소드를 사용하여 this를 관리할 수 있습니다.

    • this 값이 없거나, 변경하는 경우 call, apply, bind를 사용합니다. 메소드는 다음과 같은 차이점이 있습니다.

     

    메소드 실행 시 차이점
    call 첫 번째 인자로 사용할 this를 불러와서, 함수를 실행 this가 비어있으므로 매번 지정
    apply 첫 번째 인자로 사용할 this, 두 번째 인자로 apply(적용)할 내용 모던 js에서는 spead operator를 사용
    .call(this값, …[적용할 값들])
    bind this를 bind(묶음)해서 새 변수에 저장 this를 bind한 새로운 함수 생성

     

    2. call()

    • 첫 번째 인자로 사용할 this를 불러와서, 함수를 실행합니다.

    • 함수의 this가 비어있으므로 매번 지정해 사용합니다.
    함수명.call(this값, 전달할 값)

     

    3. apply()

    • 첫 번째 인자로 사용할 this, 두 번째 인자로 apply(적용)할 내용을 입력합니다. 

    • spead operator가 나오기 이전에 사용하던 메소드입니다.
      • 모던 자바스크립트에서는 call을 사용합니다.
    함수명.apply(this값, [적용할 값들])
    
    // 모던 자바스크립트에서는 call을 사용합니다.
    함수.call(this값, …[적용할 값들])

     

    4. bind()

    • this를 bind(묶음)해서 새 변수에 저장합니다. 바로 실행되지 않습니다.

    • 변수에 저장된 함수는 this를 매번 지정할 필요 없는 새로운 역할의 함수입니다.
    const 새함수 = 함수명.bind(this값)
    const singSingStore = {
      storeName: "과일 가게",
      location: "서울 중랑구",
      itemList: ["사과"],
      addItem: function (item: string) {
        this.itemList.push(item);
        console.log(this.itemList);
      },
    };
    
    // 그냥 호출, this
    singSingStore.addItem("버터");
    
    const snackStore = {
      storeName: "과자 가게",
      location: "서울 노원구",
      itemList: ["사탕"],
      addItem: null,
    };
    
    const addItem = singSingStore.addItem!;
    
    addItem.call(snackStore, "빼빼로");
    addItem.call(singSingStore, "빼빼로");
    
    const addSnack = addItem.bind(snackStore);
    addSnack("초코밥");
    
    const addBug = addItem.bind(snackStore, "바퀴벌레");
    addBug();
    addBug();

     

    5. bind와 eventListener (feat. this keyword)

    • eventListener는 콜백 함수를 가진 higher-order function입니다.

    • eventListener의 this keyword는 항상 이벤트가 일어날 target을 가르킵니다.
      • call 메소드는 함수를 바로 실행합니다.

      • bind 메소드는 함수를 실행하지 않습니다.

      • eventListener의 콜백 함수에서 this keyword를 사용할 때, bind를 사용하여 직접 지정해줄 수 있습니다.
    // 버튼을 누를 때마다 snackStore에 먼지가 쌓이는 코드입니다.
    const addDustBtn = document.querySelector(".addDustBtn");
    
    // bind대신 call을 사용한다면, 바로 실행되어 eventListener가 정상적으로 작동하지 않습니다.
    addDustBtn.addEventListener('click', addItem.bind(snackStore, "먼지"))
    반응형
Designed by Tistory.