1

关于这个主题有几篇文章,但找不到一篇解释 Promises 中上下文概念的文章。让我们从一些代码开始(这取自 Ember.js 模块并进行了简化,但可以是任何支持 Promise 的 JS 代码):

module.exports = CoreObject.extend({

init: function(pluginOptions, parentObject) {
//These are the properties that I want to access in methods below.
this.parentObject = parentObject;
this.propertyA = pluginOptions.propertyA;
this.propertyB = pluginOptions.propertyB;

},

startProcessing: function(whatToProcess) {
/* The following line does not work which is okay
      return this.prepareForProcessing(whatToProcess).then(process).then(postProcess(processedData, this); */

//This line does work, but parameters to then don't work. The result of prepareForProcessing is not passed to process and so on.
      return this.prepareForProcessing(whatToProcess).then(this.process).then(this.postProcess);

},

prepareForProcessing: function(whatToProcess) {
 //this does not work as 'this' is set to a different context
 //What does 'this' refer to here?
 //How do I access propertyA, propertyB defined at the beginning of this object?
  if(this.propertyA) {
  ....
}
process: function(preparedData) {
  //this does not work either
  if(this.propertyB) {
  .....
  }
}
postProces: function(processedData, options) {
 //This should work for obvious reasons but is the best way?
 if( options.propertyA) {
  ......
 }

}

}
})

现在,我的问题如下:

  1. 请参阅上面 prepareForProcessing 函数中的注释。当从 promise 的“then”方法调用时,“this”变量在方法内部指的是什么?如果我转储“this”对象,它似乎指的是某个全局节点/ember cli 对象而不是这个模块。
  2. 如何在方法中检索/访问上述属性?一种明显的方法是将选项作为参数传递,但不确定这是否是正确的方法。如果您查看此处的代码(第 34 行),则每个“then”调用都会传递选项。但是,这是否不违反 OOP 的具有可重用的类/实例级变量的原则?我对 JS 比较陌生,完全不了解基于“对象”的模型,所以如果这听起来像一个愚蠢的问题,请原谅我。

我将不胜感激任何帮助和指导。非常感谢你。

4

1 回答 1

1

您需要使用Function.prototype.bind

this.prepareForProcessing(whatToProcess).then(this.process.bind(this)).then(this.postProcess.bind(this));
于 2015-12-24T17:43:20.977 回答