2017-01-04 4 views
0

를 얻는 코드의 단순화 된 버전입니다 :중첩 된 화살표의 기능은 여기에 글로벌 범위를

class Service { 
    static _runRequest = (request, success, failure) => { 
     request.then(
      (response) => { 
       if (ResponseHelper.wasSuccessful(response)) { 
        success(response); 
       } 
       else if (ResponseHelper.wasUnauthorized(response)) { 
        SessionHelper.refreshCurrentSession().then(
         (refreshResponse) => { 
          if (refreshResponse === true) { 
           this._runRequest(request, success, failure); 
          } 
         } 
        ); 
       } 
      } 
     ); 
    } 
} 

문제는 세션이 성공적으로 갱신 된 경우 다시 _runRequest를 호출 할 때, this는 전역 범위를 가리키고 있다는 것이다.

모든 아이디어가 왜 고쳐야합니까? this은 중첩 된 함수가 몇 개 있어도 그대로 유지해야합니까? 코드 this에서

+1

작업 조각을 제공하시기 바랍니다 문제를 보여줍니다. – trincot

+3

'Service'를 가리 키기 위해서는 화살표를'_runRequest'로 사용하지 말고 정상적인 기능을 사용하십시오. – loganfsmyth

+0

@loganfsmyth 그래, 그것을 해결! 와우 예, 그들이 말하는 것처럼, 화살 기능은은 총알이 아닙니다. 동의 할 수 있도록 적절한 답을 작성하십시오. – dccarmo

답변

0

는에있는 중첩 수준의 독립, (엄격한 설정 & 환경에 따라) 전역 객체 또는 undefined 될 것입니다. 당신이 정적 메서드의 첫 번째 줄을 실행 자마자 그와 같다. 은 "클래스"개체 참조

static _runRequest(request, success, failure) { // ...etc 

이는 것 this 대신 화살표 구문 정적 메소드를 정의

, 더 확립 바로 가기 기능 표기법을 사용한다.

는 바벨을 사용하여 간단한 코드 (NO 중첩없이 약속)으로, 정적 메소드를 정의하는 두 가지 방법의 비교 내용은 아래를 참조하십시오 :

class Service1 { 
 
    static _runRequest = (i) => { 
 
     if (i == 0) { 
 
      console.log('zero'); 
 
      return; 
 
     } 
 
     if (this && '_runRequest' in this) { 
 
      return this._runRequest(0); // recurse 
 
     } 
 
     console.log('this is ' + this); 
 
    } 
 
} 
 

 
Service1._runRequest(1); 
 

 
class Service2 { 
 
    static _runRequest(i) { 
 
     if (i == 0) { 
 
      console.log('zero'); 
 
      return; 
 
     } 
 
     if (this && '_runRequest' in this) { 
 
      return this._runRequest(0); // recurse 
 
     } 
 
     console.log('this is ' + this); 
 
    } 
 
} 
 

 
Service2._runRequest(1);