본문 바로가기
Programming/Javascript

[Javascript] class 내 비동기 함수에서 this를 현재 class로 설정하는 방법

by 가가가가가가 2023. 6. 12.
반응형

 

● 문제

  - Class 내부에서 ajax나 axios와 같은 비동기 함수 사용 시 success, then과 같은 콜백 영역에서 this가 현재 class로 인식하지 못함

  - ajax : jQueyr Ajax 객체 자체를 가리킴

              "context" 옵션을 통해 명시적으로 컨텍스트 지정 가능

  - axios : then 내부에서 this는 axios의 콜백 함수에서의 컨텍스트를 가리킴

                기본적으로 "undefined"로 설정 됨

 

● 해결

  1) 화살표 함수(Arrow Function) 사용

 

// ajax 방식
$.ajax({
  url: "/api/data",
  success: response => {
    console.log(this); // 원하는 컨텍스트를 참조
    // ...
  },
  error: error => {
    console.log(error);
  }
});

// axios 방식
axios.get("/api/data")
  .then(response => {
    console.log(this); // 함수가 포함된 class 인스턴스를 참조
    // ...
  })
  .catch(error => {
    console.log(error);
  });

 

  2) bind 메소드 사용

 

// ajax 방식
$.ajax({
  url: "/api/data",
  success: function(response) {
    console.log(this); // 원하는 컨텍스트를 참조
    // ...
  }.bind(this),
  error: function(error) {
    console.log(error);
  }.bind(this)
});

// axios 방식
axios.get("/api/data")
  .then(function(response) {
    console.log(this); // 함수가 포함된 class 인스턴스를 참조
    // ...
  }.bind(this))
  .catch(function(error) {
    console.log(error);
  }.bind(this));
반응형

댓글