2017-01-04 26 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は、ネストされた関数がいくつあっても同じままではいけませんか?あなたのコードで

+1

その作業スニペットを入力してください問題を実証しています。 – trincot

+3

'Service'を指すようにしたい場合は、' _runRequest'として矢印を使用しないで、通常の関数を使用してください。 – loganfsmyth

+0

@loganfsmythこれで解決しました!うわー、彼らが言うように、矢印の機能は銀色の弾丸ではありません。私はそれを受け入れることができるように適切な回答を作成してください。 – dccarmo

答えて

0

thisは、あなたがしているネストレベルの独立したグローバルオブジェクトまたはundefined(厳密に設定&環境に応じて)、となります。それは、すぐにあなたは、静的メソッドの最初の行を実行するように、そのようなものです。

代わりの矢印構文で静的メソッドを定義する、より確立され、ショートカット機能表記法を使用:

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

これはthisが「クラス」オブジェクトを参照するであろう。

バベルを使用して簡略化されたコード(なしネストなし約束)と、静的メソッドを定義する2つの方法の比較については、以下参照:

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);

関連する問題