2016-09-27 12 views
1

コントローラのプロトタイプ関数から同じコントローラ内のプライベート関数にコンテキスト「this」が渡されるのに苦労しています。ブラウザーコンソールは「Can not未定義の "callSomeService"プロパティを読み込みます。私のコードは次のようになります:Javascriptがプロトタイプから別の関数に「this」を渡します

MyController.prototype.somemethod = function(){ 
     return somePrivateFunction() 
       .then(function (resultsFromsomePrivateFunction){ 
        return someAnotherPrivateFunction(resultsFromsomePrivateFunction) 
     }); 
} 

function somePrivateFunction(){ 
    this.callSomeService() 
     .then(function (results) { 
      return results 
      }); 
} 

function someAnotherPrivateFunction(){ 
    //dosomething 
} 

誰か助けてもらえますか?

+0

ここに何も表示されていません – Ladmerc

+0

'somePrivateFunction.call(this)' ..この値は__how__によって決まります。関数は__where__ではなく、呼び出されます... – Rayon

答えて

0

callまたはapplyを使用してコンテキストを設定できます。

return somePrivateFunction.call(this).then(...) 

OR

return somePrivateFunction.apply(this).then(...) 
+0

は動作しますが、もう1つはコード内でsomePrivateFunction.call(this).then(...) – Galileo123

+0

を返しますが、もう1つの質問が残っています。それを処理する最良の方法は何でしょうか?これをselfのようなローカル変数に代入して使うべきですか? return somePrivateFunction.call(this).then(...) – Galileo123

+0

正しく理解している場合 'then'の中で渡している'関数(resultsFromsomePrivateFunction) 'の中で' this'にアクセスすることはできません。その場合、独立した関数を作成し、bindを使って 'then'の中でそれを渡すことができます:' return somePrivateFunction()。then(newlyCreatedThenFunction.bind(this)) 'ここで' newlyCreatedThenFunction'は 'function (resultsFromsomePrivateFunction) 'を返します。それが役に立てば幸い :) –

0

あなたは、単にthisがグローバルオブジェクト、またはstrictモードでundefinedのいずれかになりますれるsomePrivateFunction()を呼んでいます。

MyController.prototype.somemethod = function(){ 
    return somePrivateFunction.call(this) 
     .then(/* ... */); 
} 

または引数としてしたいオブジェクトを渡す:あなたのいずれかを明示的にthis値を設定する.callまたは.applyを使用する必要が

MyController.prototype.somemethod = function(){ 
    return somePrivateFunction(this) 
     .then(/* ... */); 
} 

function somePrivateFunction(that){ 
    that.callSomeService() 
    /* ... */ 
} 
0

の回答はよく見るが、あなたにも設定してみる必要がありますthisを新しい変数に追加します。あなたと他の人が一緒に働くことがより簡単になります。

関連する問題