Javascript传递"this"从原型到另一个函数

Javascript passing "this" from prototype to another function

本文关键字:quot 另一个 函数 原型 this 传递 Javascript      更新时间:2023-09-26

我正在努力将上下文"this"从控制器中的原型函数传递到同一控制器中的私有函数。浏览器控制台抛出错误"无法读取未定义的属性'callSomeService' "。我的代码看起来像-

MyController.prototype.somemethod = function (){
      return somePrivateFunction()
              .then(function (resultsFromsomePrivateFunction){
                  return someAnotherPrivateFunction(resultsFromsomePrivateFunction)
       });
}
function somePrivateFunction(){
   this.callSomeService()
         .then(function (results) {
             return results 
           });
}
function someAnotherPrivateFunction(){
   //dosomething
}

谁能帮帮我?

您可以使用callapply设置上下文

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

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

您只是调用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()
    /* ... */
}