0
该主题有几个帖子,但找不到解释Promise中上下文概念的帖子。让我们从一些代码开始(这是从Ember.js模块抽取并简化,但可能是支持的承诺任何JS代码):在Promise中处理上下文的正确方法
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) {
......
}
}
}
})
现在,我的问题如下:
- 请参阅上面prepareForProcessing函数中的注释。当'promise'的方法被调用时,'this'变量在方法内引用了什么?如果我转储'this'对象,它似乎是指一些全局节点/ ember cli对象而不是这个模块。
- 如何在方法中检索/访问上述属性?一种显而易见的方式是将选项作为参数传递,但不确定这是否正确。如果您查看代码here(行号34),则会为每个“接下来的”调用传递选项。但是,这是否违背了OOP可以重用的类/实例级变量的原则?我对JS比较陌生,完全不了解基于“对象”的模型,所以请原谅我,如果这听起来像一个愚蠢的问题。
我将不胜感激任何帮助&指导。非常感谢你。
我不明白为什么'this'不会是你'prepareProcessing'会发生什么,因为你永远只通过'this'称之为:'这.prepareForProcessing(...)'。 –