2016-09-27 73 views
1

我正在努力將上下文「this」從控制器中的原型函數傳遞到同一控制器中的私有函數(s)。瀏覽器控制檯拋出錯誤「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

您可以使用callapply來設置上下文。

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

OR

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

工作,但我留下來在代碼中還有一個返回somePrivateFunction.call(this)。然後(...) – Galileo123

+0

這個工作,但我留下了一個更多的問題,「這個」在這裏之後再次失去其參考。什麼是最好的方法來處理?我應該將它分配給像self這樣的局部變量並使用它嗎?返回somePrivateFunction.call(this).then(...) – Galileo123

+0

如果我理解正確你不能在函數(resultsFromsomePrivateFunction)裏面訪問'this',你在'then'裏面傳入。如果是這種情況,你可以創建一個獨立的函數,然後在'then'內使用bind來傳遞它,例如:'return somePrivateFunction()。then(newlyCreatedThenFunction.bind(this))'''newCreatedThenFunction''''' (resultsFromsomePrivateFunction)'。希望能幫助到你 :) –

0

你只是呼籲somePrivateFunction(),爲此this位將是全局對象,或者undefined嚴格模式。你要麼需要使用.call.apply明確設置this值:

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

或者通過你想作爲參數的對象:

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

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

提供的答案看起來不錯,但你也應該嘗試設置this到一個新的變量。你和其他人一起工作會更容易。

相關問題